[英]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.