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

前端 未结 5 382
小鲜肉
小鲜肉 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:50

    Using a list comprehension when you only need the first just feels slimy (to me). Use a for-loop and exit early.

    >>> lst = [None, None, None, "foo", None]
    >>> for i, item in enumerate(lst):
    ...   if item: break
    ... else:
    ...   print "not found"
    ... 
    >>> i
    3
    

提交回复
热议问题