-1

我想知道是否有更多的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)
4

1 回答 1

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全局是一个列表。请注意,传入服务然后返回结果会更好:

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)
于 2012-12-20T09:15:38.983 回答