Pythonic way to combine FOR loop and IF statement

后端 未结 10 2371
暗喜
暗喜 2020-11-27 09:02

I know how to use both for loops and if statements on separate lines, such as:

>>> a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
... for x in         


        
10条回答
  •  抹茶落季
    2020-11-27 09:56

    I liked Alex's answer, because a filter is exactly an if applied to a list, so if you want to explore a subset of a list given a condition, this seems to be the most natural way

    mylist = [1,2,3,4,5]
    another_list = [2,3,4]
    
    wanted = lambda x:x in another_list
    
    for x in filter(wanted, mylist):
        print(x)
    

    this method is useful for the separation of concerns, if the condition function changes, the only code to fiddle with is the function itself

    mylist = [1,2,3,4,5]
    
    wanted = lambda x:(x**0.5) > 10**0.3
    
    for x in filter(wanted, mylist):
        print(x)
    

    The generator method seems better when you don't want members of the list, but a modification of said members, which seems more fit to a generator

    mylist = [1,2,3,4,5]
    
    wanted = lambda x:(x**0.5) > 10**0.3
    
    generator = (x**0.5 for x in mylist if wanted(x))
    
    for x in generator:
        print(x)
    

    Also, filters work with generators, although in this case it isn't efficient

    mylist = [1,2,3,4,5]
    
    wanted = lambda x:(x**0.5) > 10**0.3
    
    generator = (x**0.9 for x in mylist)
    
    for x in filter(wanted, generator):
        print(x)
    

    But of course, it would still be nice to write like this:

    mylist = [1,2,3,4,5]
    
    wanted = lambda x:(x**0.5) > 10**0.3
    
    # for x in filter(wanted, mylist):
    for x in mylist if wanted(x):
        print(x)
    

提交回复
热议问题