简体   繁体   中英

Find the index list element in a list of lists

I'm trying to list.index the first occurrence of a variable in a list element within a list of lists. For example:

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

I would like to do something like:

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

So far, I am trying to achieve this with the following piece of code:

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

But , I woud like to find a more pythonic solution to my problem.

Are you sure you are using the best data structure? Can not you rethink your program so that it generates something more compellable? Such nested lists are either anti-pythonic...

Anyway, why I would recommand with your code as it is to use next() and enumerate() :

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

An option would be using while to loop over 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

Output:

>>> 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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