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

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

    Exiting at the first match is really easy: instead of computing a full list comprehension (then tossing away everything except the first item), use next over a genexp. Assuming for example that you want -1 when no item satisfies the condition of being != x,

    return next((i for i, v in enumerate(L) if v != x), -1)
    

    This is Python 2.6 syntax; if you're stuck with 2.5 or earlier, .next() is a method of the genexp (or other iterator) and doesn't accept a default value like the -1 above (so if you don't want to see a StopIteration exception you'll have to use a try/except). But then, there is a reason more releases were made after 2.5 -- continuous improvement of the language and its built-ins!-)

提交回复
热议问题