首页 > 解决方案 > 比较两个重复的字符串列表并打印差异

问题描述

我对 Python 很陌生,我的代码有问题。我想编写一个与列表进行比较并打印给用户的函数,哪些元素存在于 list1 中但不存在于 lis2 中。

例如输入可以是:

list1=["john", "jim", "michael", "bob"]
list2=["james", "edward", "john", "jim"]

然后输出应该是:

Names in list1, but not in list2: Michael, Bob
Names in list2, but not in list1: James, Edward

谢谢你的帮助!

(编辑:这是我到目前为止的代码:

def compare_lists(list1, list2):

    for name1 in list1:
        if name1 not in list2:
                  print("Names in list1, but not in list2: ", name1)

    for name2 in list2:
        if name2 not in list1:
                 print("Names in list1, but not in list2: ", name2)

我的问题是输出打印了两次:

Names in list1, but not in list2: Michael
Names in list1, but not in list2: Bob
Names in list2 but not in list1: James
Names in list2 but not in list1: Edward

标签: pythonlistcompare

解决方案


尝试这个:

list1=["john", "jim", "michael", "bob"]
list2=["james", "edward", "john", "jim"]

names1 = [name1 for name1 in list1 if name1 not in list2]
names2 = [name2 for name2 in list2 if name2 not in list1] 
print(names1)
print(names2)

推荐阅读