简体   繁体   中英

python: comparing values in a list if exists in another list

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)

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

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. :)

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.

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