我在python中有这个多维数组。
hello = [(['b', 'y', 'e'], 3), (['h', 'e', 'l', 'l', 'o'], 5), (['w', 'o', 'r', 'l', 'd'], 5)]
我希望找到数字3的索引,我尝试使用hello.index(3)但不起作用。任何解决方案?
答案 0 :(得分:5)
>>> [x[0] for x in hello if x[1] == 3][0]
['b', 'y', 'e']
如果您需要项目索引,请尝试
>>> [i for i, x in enumerate(hello) if x[1] == 3][0]
0
对于多个结果,请在结尾删除[0]
:
>>> hello.append((list("spam"), 3))
>>> hello
[(['b', 'y', 'e'], 3), (['h', 'e', 'l', 'l', 'o'], 5), (['w', 'o', 'r', 'l', 'd'], 5), (['s', 'p', 'a', 'm'], 3)]
>>> [x[0] for x in hello if x[1] == 3]
[['b', 'y', 'e'], ['s', 'p', 'a', 'm']]
>>> [i for i, x in enumerate(hello) if x[1] == 3]
[0, 3]
>>>
答案 1 :(得分:0)
试试这个,
>>> [ i for i in hello if i[1] == 3 ]
[(['b', 'y', 'e'], 3)]