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

后端 未结 7 803
面向向阳花
面向向阳花 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条回答
  •  梦毁少年i
    2020-11-21 06:49

    Second is better.

    Think of the person who would need to understand your code. You can get bad karma easily with the first :)

    You could go middle between the two by using filter(). Consider the example:

    y=[1,2,3,4,5,6]
    def func(x):
        print "call with %r"%x
    
    for x in filter(lambda x: x>3, y):
        func(x)
    

提交回复
热议问题