比较两个重复的字符串列表并打印差异

时间:2018-10-28 12:49:32

标签: python list compare

我是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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)