简体   繁体   中英

Compare two lists of strings with duplicates and print differences

I'm very new to Python and are having problems with my code. I want to write a function that compares to lists and prints to the user, which elements exist in list1 but not in lis2.

For example the input can be:

list1=["john", "jim", "michael", "bob"]
list2=["james", "edward", "john", "jim"]

And then the output should be:

Names in list1, but not in list2: Michael, Bob
Names in list2, but not in list1: James, Edward

Thank you your help!

(EDIT: this is my code so far:

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)

And my problem is that the output is printed twice:

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

Try this:

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)

You could store the result in a temp string, then print them out.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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