繁体   English   中英

带有元组的python列表迭代存在并获取索引

[英]python list with tuple iterate for existence and get the index

我有包含元组的python列表,我想检查列表中所有元组中元组的第一个元素,我设法做到这一点,如下所示:

x = [('a',1), ('b',2), ('c',3)]
if 'a' in ([y[0] for y in x]):
    //how to get the index of the tuple that 'a' exist

我想要在元组的索引中存在上面的示例“ a”。

您可以使用next()

next(i for i in xrange(0, len(x)) if x[i][0] == 'a')

请注意,如果找不到a则将获得StopIteration异常。 您还可以提供默认值以返回一个值:

next((i for i in xrange(0, len(x)) if x[i][0] == 'd'), -1)

演示:

>>> next(i for i in xrange(0, len(x)) if x[i][0] == 'a')
0
>>> next((i for i in xrange(0, len(x)) if x[i][0] == 'd'), -1)
-1

enumerate()也可以在这里用于获取索引值:

>>> next(i for i, (a, _) in enumerate(x) if a == 'a')
0
>>> next((i for i, (a, _) in enumerate(x) if a == 'd'), -1)
-1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM