мой входной файл:Как распечатать клонированный список один раз и загрузить их в словаре в Python?
cs 124456 powerful cs 124456 powerful me 125454 easy me 125455 easy me 125455 easy ec 125555 done ec 127678 fine ec 127678 fine ci 127678 fine ci 127678 fine eee 125678 good eee 125678 good eee 125678 good eee 125678 bad`
Ожидаемый результат:
no.name reg perform 1.cs 124456 powerful 2.me 125454 easy 3.me 125455 easy 4.ec 125555 done 5.ec 127678 fine 6.ci 127678 fine 7.eee 125678 good 8.eee 125678 bad
мой код:
import os os.chdir("d:/filer") import re def first(line): f=re.findall("[a-z]+",line,flags=0) return f def num(line): n=re.findall("\d{6}",line,flags=0) return n with open("once.txt","r") as sa: for line in sa.readlines(): home=first(line) number=num(line) x=home[0] y=number[0] z=home[1] if x!=0 and y!=0 and z!=0: print [x,y,z]
Я открыл файл и читать их построчно. Затем я извлек эти числа и текст, используя регулярное выражение, и сохранил их в списке с индексами. Теперь я хочу только списки, которые уникальны и не клонируются. Затем загрузите их в словарь. Может кто-нибудь мне помочь?
0
A
ответ
0
Для того, чтобы предотвратить клонирование, вы можете использовать set()
так:
results = set() # Construct a set
with open("once.txt","r") as sa:
for line in sa.readlines():
home=first(line)
number=num(line)
x=home[0]
y=number[0]
z=home[1]
if x!=0 and y!=0 and z!=0:
if (x,y,z) not in results: # Check if the set already contains the result
results.add((x,y,z)) # If it doesn't, add to the set and print.
print [x,y,z]
Я также предлагаю организовать свой небольшой фрагмент кода. Вы можете просто создать 1 регулярное выражение для ясности следующим образом:
results = set() # Construct a set
with open("once.txt","r") as sa:
count = 0
for line in sa: # No need for readlines()
match = re.match(r"(\w+)\s+(\d+)\s+(\w+)")
if match is None:
continue
result = match.groups()
if result not in results: # Check if the set already contains the result
count += 1
results.add(result) # If it doesn't, add to the set and print.
print count, result