在 Python 中,如何找到不是某个值的列表中第一项的索引? [英] In Python, how can I find the index of the first item in a list that is NOT some value?

查看:13
本文介绍了在 Python 中,如何找到不是某个值的列表中第一项的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 的列表类型有一个 index(x) 方法.它接受一个参数 x,并返回列表中具有值 x 的第一项的(整数)索引.

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.

基本上,我需要反转 index(x) 方法.我需要获取没有值 x 的列表中第一个值的索引.我什至可能只使用一个函数来返回第一个项目的索引,值为 != None.

Basically, I need to invert the index(x) method. I need to get the index of the first value in a list that does NOT have the value x. I would probably be able to even just use a function that returns the index of the first item with a value != None.

我可以想到一个带有递增计数器变量的for"循环实现,但我觉得我错过了一些东西.是否有可以处理此问题的现有方法或单行 Python 构造?

I can think of a 'for' loop implementation with an incrementing counter variable, but I feel like I'm missing something. Is there an existing method, or a one-line Python construction that can handle this?

在我的程序中,当我处理从复杂的正则表达式匹配返回的列表时会出现这种情况.每个列表中除一项外的所有项的值为 None.如果我只需要匹配的字符串,我可以使用像[x for x in [my_list] if x is not None]"这样的列表推导式,但我需要索引以找出我的正则表达式中的哪个捕获组实际上导致比赛.

In my program, the situation comes up when I'm handling lists returned from complex regex matches. All but one item in each list have a value of None. If I just needed the matched string, I could use a list comprehension like '[x for x in [my_list] if x is not None]', but I need the index in order to figure out which capture group in my regex actually caused the match.

推荐答案

在第一场比赛中退出真的很容易:而不是计算一个完整的列表理解(然后扔掉除了第一项之外的所有内容),使用 next 在 genexp 上.例如,假设您想要 -1 当没有项目满足 != x 的条件时,

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)

这是 Python 2.6 语法;如果您坚持使用 2.5 或更早版本,.next() 是 genexp(或其他迭代器)的一种方法,并且不接受像 -1 以上(因此,如果您不想看到 StopIteration 异常,则必须使用 try/except).但是, 是在 2.5 之后发布更多版本的原因——语言及其内置程序的持续改进!-)

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!-)

这篇关于在 Python 中,如何找到不是某个值的列表中第一项的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆