简体   繁体   中英

More pythonic way to write this function

I wonder if there any more pythonic way to write this function:

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)

Use sets:

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)

This presumes the services global is a list. Note that it'd be much better to pass in services then return the result:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM