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



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

相关内容

  • 没有找到相关文章

最新更新