Is it Pythonic to use list comprehensions for just side effects?

后端 未结 7 691
面向向阳花
面向向阳花 2020-11-21 06:23

Think about a function that I\'m calling for its side effects, not return values (like printing to screen, updating GUI, printing to a file, etc.).

def fun_wi         


        
7条回答
  •  离开以前
    2020-11-21 06:56

    You shouldn't use a list comprehension, because as people have said that will build a large temporary list that you don't need. The following two methods are equivalent:

    consume(side_effects(x) for x in xs)
    
    for x in xs:
        side_effects(x)
    

    with the definition of consume from the itertools man page:

    def consume(iterator, n=None):
        "Advance the iterator n-steps ahead. If n is none, consume entirely."
        # Use functions that consume iterators at C speed.
        if n is None:
            # feed the entire iterator into a zero-length deque
            collections.deque(iterator, maxlen=0)
        else:
            # advance to the empty slice starting at position n
            next(islice(iterator, n, n), None)
    

    Of course, the latter is clearer and easier to understand.

提交回复
热议问题