Python: Find in list

后端 未结 10 725
故里飘歌
故里飘歌 2020-11-22 10:15

I have come across this:

item = someSortOfSelection()
if item in myList:
    doMySpecialFunction(item)

but sometimes it does not work with

相关标签:
10条回答
  • 2020-11-22 10:55

    While the answer from Niklas B. is pretty comprehensive, when we want to find an item in a list it is sometimes useful to get its index:

    next((i for i, x in enumerate(lst) if [condition on x]), [default value])
    
    0 讨论(0)
  • 2020-11-22 10:55

    Another alternative: you can check if an item is in a list with if item in list:, but this is order O(n). If you are dealing with big lists of items and all you need to know is whether something is a member of your list, you can convert the list to a set first and take advantage of constant time set lookup:

    my_set = set(my_list)
    if item in my_set:  # much faster on average than using a list
        # do something
    

    Not going to be the correct solution in every case, but for some cases this might give you better performance.

    Note that creating the set with set(my_list) is also O(n), so if you only need to do this once then it isn't any faster to do it this way. If you need to repeatedly check membership though, then this will be O(1) for every lookup after that initial set creation.

    0 讨论(0)
  • 2020-11-22 10:58

    If you want to find one element or None use default in next, it won't raise StopIteration if the item was not found in the list:

    first_or_default = next((x for x in lst if ...), None)
    
    0 讨论(0)
  • 2020-11-22 10:58

    Finding the first occurrence

    There's a recipe for that in itertools:

    def first_true(iterable, default=False, pred=None):
        """Returns the first true value in the iterable.
    
        If no true value is found, returns *default*
    
        If *pred* is not None, returns the first item
        for which pred(item) is true.
    
        """
        # first_true([a,b,c], x) --> a or b or c or x
        # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
        return next(filter(pred, iterable), default)
    

    For example, the following code finds the first odd number in a list:

    >>> first_true([2,3,4,5], None, lambda x: x%2==1)
    3  
    
    0 讨论(0)
提交回复
热议问题