1

I want to fetch the inner list from 'list1' when the second colomn element of 'list1' matches with the element coming in loop of 'list2'

I have a list like this:

list1=
    [
        [1546,'token1',12,442],
        [23,'token2',4,542],
        [6,'token3',34,462],
        [336,'token4',45,642],
        [146,'token5',43,62],
    ]

and another list :

list2=['token1','token2','token3','token4','token5']



 for element in list2:

Here I want if element == list1 second colomn element (i.e. 'token1'==list1's second colomn element 'token1')
then I get the list [ID,element,value1,value2] (ie [1546,'token1',12,442]) from list1.

Ali Abbas
  • 45
  • 5
  • Looks like you are wanting to filter the list. Take a look at this answer to see if it helps. https://stackoverflow.com/a/23862438/2793683 – dmoore1181 Feb 13 '19 at 19:32

4 Answers4

1

you could try:

dict_from_list_1 = {e[1]: e for e in list1}
for element in list2:
    if element in dict_from_list_1:
        print(dict_from_list_1[element])
kederrac
  • 15,339
  • 4
  • 25
  • 45
  • Second soluiton cannot work with this list correctly while the first one will. **list2=['token4','token2','token3']** – Ali Abbas Feb 13 '19 at 20:12
  • if you want to save some memory, in first exemple you could save in the dict as value the position of your list in list1 – kederrac Feb 13 '19 at 20:18
  • You have given three answer. First one is fine. Second one time complexity is more. Third one is not correct. @rusu_ro1 – Ali Abbas Feb 13 '19 at 20:33
0

List comprehension is a really simple and powerful way of doing so:

lista = [[i for i in list1 if token in i] for token in list2]

print([each[0] for each in lista if len(each)])

Output:

[[1546, 'token1', 12, 442], [23, 'token2', 4, 542], [6, 'token3', 34,462], [336, 'token4', 45, 642], [146, 'token5', 43, 62]]
0

You can create a dict for lookup using a dictcomp and fetch data into the list using a listcomp:

d = {i[1]: i for i in list1}
l = [d[i] for i in list2]
Mykola Zotko
  • 8,778
  • 2
  • 14
  • 39
0

These are two ways of doing this that will produce the result you want. Let me show the long way:

for i in list1:
    if i[1] in list2:
        print (i)

Then here we can use a Generator to achieve the above in one line.

[element for element in list1 if element[1] in list2]

Hope this helps.

Cesar17
  • 91
  • 5