Pythonic way to combine FOR loop and IF statement

后端 未结 10 2331
暗喜
暗喜 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 10:00

    I personally think this is the prettiest version:

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    for x in filter(lambda w: w in a, xyz):
      print x
    

    Edit

    if you are very keen on avoiding to use lambda you can use partial function application and use the operator module (that provides functions of most operators).

    https://docs.python.org/2/library/operator.html#module-operator

    from operator import contains
    from functools import partial
    print(list(filter(partial(contains, a), xyz)))
    
    0 讨论(0)
  • 2020-11-27 10:02

    The following is a simplification/one liner from the accepted answer:

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    
    for x in (x for x in xyz if x not in a):
        print(x)
    
    12
    242
    

    Notice that the generator was kept inline. This was tested on python2.7 and python3.6 (notice the parens in the print ;) )

    0 讨论(0)
  • 2020-11-27 10:04
    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]  
    set(a) & set(xyz)  
    set([0, 9, 4, 6, 7])
    
    0 讨论(0)
  • 2020-11-27 10:05

    Use intersection or intersection_update

    • intersection :

      a = [2,3,4,5,6,7,8,9,0]
      xyz = [0,12,4,6,242,7,9]
      ans = sorted(set(a).intersection(set(xyz)))
      
    • intersection_update:

      a = [2,3,4,5,6,7,8,9,0]
      xyz = [0,12,4,6,242,7,9]
      b = set(a)
      b.intersection_update(xyz)
      

      then b is your answer

    0 讨论(0)
提交回复
热议问题