我想知道是否有更多的pythonic方式来编写这个函数:
def parse(filename):
with open(filename, 'r', encoding='koi8-r') as f:
for log_line in f:
for s in services:
if ' ' + s + ' ' in log_line:
print(s)
services.remove(s)
答案 0 :(得分:2)
使用套装:
def parse(filename):
servicesset = set(services)
with open(filename, 'r', encoding='koi8-r') as f:
for log_line in f:
words = set(log_line.split())
servicesset -= words
services[:] = list(servicesset)
这假定services
global是一个列表。请注意,在服务中传递然后返回结果会更好 :
def parse(filename, services):
services = set(services)
with open(filename, 'r', encoding='koi8-r') as f:
for log_line in f:
words = set(log_line.split())
services -= words
return list(servicesset)