0

Anyone can help me, I have a list 2D and I want to know index of myList in 2D, but I just know first value of that index, for example I just know 'a2' and I want to know index of list that contain 'a2' in first value because I want to access that list example I wanna to access ['a2', 'b1'] by know 'a2' :

myList2= [['a1', 'b2', 'c1'], ['a2', 'b1'], ['b1', 'c2'], ['b2', 'c1'], ['c1'], ['c2']]

Other case....if myList2 is a list of object of class point.

Erna Piantari
  • 547
  • 2
  • 11
  • 26
  • Also see [here](http://stackoverflow.com/questions/11963711/what-is-the-most-efficient-way-to-search-nested-lists-in-python), [here](http://stackoverflow.com/questions/6889785/python-how-to-search-an-item-in-a-nested-list), and lots more similar questions. – TigerhawkT3 Dec 22 '15 at 06:22

2 Answers2

0

This will do:

for element in [i for i in myList2 if i[0]=='a2']:
    #do something with element

Or,

for element in filter(lambda x:x[0]=='a2',myList2):
    #do something
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
  • @AvinashRaj, edited. – Ahsanul Haque Dec 22 '15 at 06:25
  • I have another problem when iterate can't find list with first value that I set. for example `my list= [['a1', 'b2', 'c1'], ['b1', 'c2'], ['b2', 'c1'], ['c1'], ['c2']]` and my code is `for element in [i for i in myList2 if i[0]=='a2']:` . would you can give me any advise? – Erna Piantari Dec 22 '15 at 12:48
  • In your code, `element` is a list. So, you can access each item of that list. You may access specific item of that list with index or in case if you want to iterate over the list, you may use a for loop. – Ahsanul Haque Dec 22 '15 at 15:47
0

You can check if the element you know, in this case 'a2' is in any of the nested lists. If so, you can print that list.

>>> myList2= [['a1', 'b2', 'c1'], ['a2', 'b1'], ['b1', 'c2'], ['b2', 'c1'], ['c1'], ['c2']]
>>> for i in myList2:
    if 'a2' in i:
        print i


['a2', 'b1']
>>> 
Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48