如何一次打印克隆列表并将它们加载到Python中的字典中?
问题描述:
-
我输入文件:如何一次打印克隆列表并将它们加载到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]
我打开的文件,并通过行阅读线。然后我使用正则表达式提取这些数字和文本,并将其存储在带索引的列表中。现在我只想列出那些唯一且不克隆的列表。然后将它们加载到字典中。有人能帮助我吗?
答
为了防止克隆,你可以使用一个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