繁体   English   中英

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

[英]Compare two lists of strings with duplicates and print differences

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

尝试这个:

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)

您可以将结果存储在临时字符串中,然后将其打印出来。

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)

暂无
暂无

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

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