发布于 2016-09-24 12:21:18
为了防止克隆,您可以使用类似的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
https://stackoverflow.com/questions/39674028
复制相似问题