In Python, how can I find the index of the first item in a list that is NOT some value?

前端 未结 5 389
小鲜肉
小鲜肉 2020-12-14 20:14

Python\'s list type has an index(x) method. It takes a single parameter x, and returns the (integer) index of the first item in the list that has the value x.

Basica

5条回答
  •  庸人自扰
    2020-12-14 20:34

    [i for i, x in enumerate(my_list) if x != value][0]
    

    If you're not sure whether there's a non-matching item, use this instead:

    match = [i for i, x in enumerate(my_list) if x != value]
    if match:
        i = match[0]
        # i is your number.
    

    You can make this even more "functional" with itertools, but you will soon reach the point where a simple for loop is better. Even the above solutions aren't as efficient as a for loop, since they construct a list of all non-matching indices before you pull the one of interest.

提交回复
热议问题