我很新手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