![](/img/trans.png)
[英]In Python, how can I find the index of the first item in a list that is NOT some value?
[英]Python find the index of an item in a list where some columns are not important
我在python中有一个列表,如下例所示: a = [[1,2,'aaa'] , [3,4,'nnnn']
我如何只说[1,2,*]来获得[1,2,'aaa']的索引,其中*表示不重要? 换句话说,我想获取第一列为1且第二列为2且第三列值不重要的项目的索引。
您可以使用扩展的可迭代拆包 :
a = [[1, 2, 'aaa'], [3, 4, 'nnnn']]
indices = [i for i, (first, second, *_) in enumerate(a) if (first, second) == (1, 2)]
print(indices)
输出量
[0]
您可以使用operator.itemgetter
作为扩展解决方案:
from operator import itemgetter
a = [[1,2,'aaa'] , [3,4,'nnnn']]
getter = itemgetter(0, 1) # get first and second items
indices = [idx for idx, item in enumerate(a) if getter(item) == (1, 2)] # [0]
简单循环如何?
a = [[1,2,'aaa'] , [3,4,'nnnn']
for i, item in enumerate(a):
if item[0] == 1 and item[1] == 2:
print(i)
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.