简体   繁体   English

python:如果存在于另一个列表中,则比较列表中的值

[英]python: comparing values in a list if exists in another list

So now I have 2 lists,所以现在我有 2 个列表,

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.我想比较 list1 中的所有第二个元素,如果它存在于 list2 中,则打印相应的列表。 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 循环,但我认为我做错了什么

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:您可以将list2转换为字典以便更快地查找:

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: 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.您的代码在通过索引访问值时遇到了一些问题,并且您在使用之前没有将 fstore 分配为空列表。

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: 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: 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.当然,如果您愿意,可以使用“[]”切换创建元组列表的列表推导中的“()”以创建列表列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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