2013-07-31 56 views
0

我在python中有這個多維數組。在python中搜索多維數組中的項目

hello = [(['b', 'y', 'e'], 3), (['h', 'e', 'l', 'l', 'o'], 5), (['w', 'o', 'r', 'l', 'd'], 5)] 

我想找到編號爲3的索引,我嘗試使用hello.index(3),但不起作用。任何解決方案

回答

0

嘗試這樣,

>>> [ i for i in hello if i[1] == 3 ] 
[(['b', 'y', 'e'], 3)] 
4
>>> [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] 
>>> 
+0

什麼關於多重結果? –

+0

@AdemÖztaş:'index()'只發現第一次出現,所以這個解決方案確實有意義。 – sberry

+0

更改了答案 –