簡體   English   中英

在列表列表中找到索引列表元素

[英]Find the index list element in a list of lists

我正在嘗試list.index在列表列表中的list元素中第一次出現變量。 例如:

myList = [[[(0,0),(1,1)],'add',10],[[(0,0),(1,1)],'add',10] . . . ]

我想做類似的事情:

index = myList.index((0,0))
myList[index] : [[(0,0),(1,1)],'add',10]

到目前為止,我正在嘗試通過以下代碼來實現:

i = 0
for cage in myList:
    if cage[0][0] == A:
       print('Found')
       break
    i += 1
print(self.Cages[i])

但是,我想為我的問題找到一個更加Python化的解決方案。

您確定使用的是最佳數據結構嗎? 您不能重新考慮您的程序,使其產生更可強迫的東西嗎? 這樣的嵌套列表要么是反Python的...

無論如何,為什么我要重新使用您的代碼,因為要使用next()enumerate()

index = next(i for i, x in enumerate(myList) if x[0][0] == A)

一個選項是使用while循環遍歷iter(my_list)

my_list = [[[(0,0),(1,1)],'add',10],[[(0,0),(1,1)],'add',10]]

my_iterator = iter(my_list)

item = next(my_iterator)
while (0, 0) not in item[0]:
    item = next(my_iterator)

print item

輸出:

>>> my_list = [[[(2,2),(1,1)],'add',10], [[(0,0),(1,1)],'add',10], [[(3,3),(1,1)],'add',10]]
>>>
>>> my_iterator = iter(my_list)
>>>
>>> item = next(my_iterator)
>>> while (0, 0) not in item[0]:
...     item = next(my_iterator)
...
>>> print item
[[(0, 0), (1, 1)], 'add', 10]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM