How to compare all items in a list with an integer without using for loop

前端 未结 6 1843
臣服心动
臣服心动 2021-01-14 06:25

I have a couple of lists which vary in length, and I would like to compare each of their items with an integer, and if any one of the items is above said integer, it breaks

相关标签:
6条回答
  • 2021-01-14 07:00

    Don't use list as a variable name, it shadows the builtin list(). There is a builtin function called any which is useful here

    if any(x>70 for x in the_list):
    

    The part inbetween the ( and ) is called a generator expression

    0 讨论(0)
  • 2021-01-14 07:02

    Well, I'd probably do it using the generator expression, but since no one else has suggested this yet, and it doesn't have an (explicit) nested loop:

    >>> lol = [[1,2,3],[4,40],[10,20,30]]
    >>> 
    >>> for l in lol:
    ...     if max(l) > 30:
    ...         continue
    ...     print l
    ... 
    [1, 2, 3]
    [10, 20, 30]
    
    0 讨论(0)
  • 2021-01-14 07:03

    If you're using python 2.5 or greater, you can use the any() function with list comprehensions.

    for list in listoflists:
      if any([i > 70 for i in list]):
        continue
    
    0 讨论(0)
  • 2021-01-14 07:04

    You can shorten it to this :D

    for good_list in filter(lambda x: max(x)<=70, listoflists):
       # do stuff
    
    0 讨论(0)
  • 2021-01-14 07:04

    Using the builtin any is the clearest way. Alternatively you can nest a for loop and break out of it (one of the few uses of for-else construct).

    for lst in listoflists:
        for i in lst:
            if i > 70:
                break
        else:
            # rest of your code
            pass
    
    0 讨论(0)
  • 2021-01-14 07:20

    You can use the built-in function any like this:

    for list in listoflists:
        if any(x < 70 for x in list):
            continue
    

    The any function does short-circuit evaluation, so it will return True as soon as an integer in the list is found that meets the condition.

    Also, you should not use the variable list, since it is a built-in function.

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