1

So now I have 2 lists,

list1 = [[0,1],[0,2],[0,10]]
list2 = [[1, ['miniwok', 'food1']], [2,['chicken', 'food2']], [3,['duck', 'food3']], ..... , [10, ['pizza', 'food10']]]

I want to compare the all 2nd element in list1 and if it exists in list2, print the corresponding list. so the result I want is something like this:

[[1, 'miniwok'],[2, 'chicken'],[10,'pizza']]

I tried using nested for loop but I think I'm doing something wrong

for x in range(len(list1)):
    for y in range(1, len(list2)+1):
        if(list1[x][1] == list2[y]):
            result = [y, list2[y][0]]
            fstore.append(result)
1
  • Is it possible to modify the code which generates those lists to use dictionaries, which will be both more performant (accessing the "random" element with O(1)), and simpler to use? This is assuming your keys (2nd integers) are unique. Commented Nov 10, 2019 at 8:23

3 Answers 3

2

You can convert list2 to a dictionary for faster lookup:

list1 = [[0,1],[0,2],[0,10]]
list2 = [[1, ['miniwok', 'food1']], [2,['chicken', 'food2']], [3,['duck', 'food3']], [10, ['pizza', 'food10']]]
new_l2 = dict(list2)
result = [[b, k[a]] for a, b in list1 if (k := new_l2.get(b)) is not None]

Output:

[[1, 'miniwok'], [2, 'chicken'], [10, 'pizza']]
Sign up to request clarification or add additional context in comments.

1 Comment

It's worth mentioning that the := operator is new from python 3.8.
1

Your code had some problems with accessing values via indexing and you haven't assigned fstore as empty list before using it.

The corrected version of your answer is here-

list1 = [[0,1],[0,2],[0,10]]
list2 = [[1, ['miniwok', 'food1']], [2,['chicken', 'food2']], [3,['duck', 'food3']], [10, ['pizza', 'food10']]]
fstore = []
for x in range(len(list1)):
    for y in range(len(list2)):
        if(list1[x][1] == list2[y][0]):
            result = [list2[y][0], list2[y][1][0] ]
            fstore.append(result)
            break

Contents of fstore:

[[1, 'miniwok'], [2, 'chicken'], [10, 'pizza']]

I hope it might help you. If you have any doubt, you can ask in comments. :)

Comments

0

You can do:

list1 = [[0,1],[0,2],[0,10]]
list2 = [[1, ['miniwok', 'food1']], [2,['chicken', 'food2']], [3,['duck', 'food3']],... , [10, ['pizza', 'food10']]]
numbers = [number[1] for number in list1]
[(item[0], item[1][0]) for item in list2 if item[0] in numbers]

Output:

[(1, 'miniwok'), (2, 'chicken'), (10, 'pizza')]

Of course the "()" in the list comprehension that creates a list of tuples can be switched with "[]" to create a list of lists, if you prefer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.