比较两个包含重复字符串的列表并打印出不同之处

3
我很新手Python,我的代码有问题。我想编写一个函数,比较两个列表并向用户打印出仅存在于list1中而不在list2中的元素。
例如输入可以是:
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

您能否编辑您的问题,并将代码以格式化的形式包含在里面? - kyriakosSt
很好,事实上你可以在这篇文章中找到你要寻找的答案:https://dev59.com/OGw15IYBdhLWcg3wo9Rx - kyriakosSt
你的代码实际上是可以工作的。你的第二个打印语句与第一个具有相同的文本,可能这就是你感到困惑的原因。要在同一行中打印名称,你所需要做的就是将它们附加到两个列表中,而不是直接打印它们。 - kyriakosSt
2
该问题可能是Python计算列表差异的重复。 - kyriakosSt
如果你有一个字符串列表,那么你可以遍历它并逐个打印出来。 - kyriakosSt
显示剩余2条评论
2个回答

2

试试这个:

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)

0
你可以将结果存储在一个临时字符串中,然后打印出来。
def compare_lists(list1, list2):

    str1 = ''
    for name1 in list1:
        if name1 not in list2:
            str1 += name1 + ' '
    print("Names in list1, but not in list2: ", str1)

    str2 = ''
    for name2 in list2:
        if name2 not in list1:
            str2 += name2 + ' '
    print("Names in list1, but not in list2: ", str2)

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

compare_lists(list1, list2)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接