List comprehension vs. lambda + filter

前端 未结 14 2143
挽巷
挽巷 2020-11-22 02:01

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.

My code looked like this:



        
14条回答
  •  时光说笑
    2020-11-22 03:00

    Here's a short piece I use when I need to filter on something after the list comprehension. Just a combination of filter, lambda, and lists (otherwise known as the loyalty of a cat and the cleanliness of a dog).

    In this case I'm reading a file, stripping out blank lines, commented out lines, and anything after a comment on a line:

    # Throw out blank lines and comments
    with open('file.txt', 'r') as lines:        
        # From the inside out:
        #    [s.partition('#')[0].strip() for s in lines]... Throws out comments
        #   filter(lambda x: x!= '', [s.part... Filters out blank lines
        #  y for y in filter... Converts filter object to list
        file_contents = [y for y in filter(lambda x: x != '', [s.partition('#')[0].strip() for s in lines])]
    

提交回复
热议问题