Side-effects in python map (python “do” block)

前端 未结 2 747
借酒劲吻你
借酒劲吻你 2020-12-11 19:02

What is the preferred way to tell someone \"I want to apply func to each element in iterable for its side-effects.\"

# Option 1...          


        
2条回答
  •  悲哀的现实
    2020-12-11 19:54

    This has been asked many times, e.g., here and here. But it's an interesting question, though. List comprehensions are meant to be used for something else.

    Other options include

    1. use map() - basically the same as your sample
    2. use filter() - if your function returns None, you will get an empty list
    3. Just a plain for-loop

    while the plain loop is the preferable way to do it. It is semantically correct in this case, all other ways, including list comprehension, abuse concepts for their side-effect.

    In Python 3.x, map() and filter() are generators and thus do nothing until you iterate over them. So we'd need, e.g., a list(map(...)), which makes it even worse.

提交回复
热议问题