简体   繁体   中英

Compare 2 list and append in new list using python

group1 = [1, 2, 3, 4, 5]

group2 = [9, 8, 7, 6, 5]

a=[]
n=[]

for k in group1:

    for v in group2:

        if k == v:
            a.append(k)
            print("a=",a)
        else:
            n.append(k)
            print("n=",n)

The following output is required:

a=[5]
n=[1,2,3,4]

Please help me to get the required output, thanks!

The reason why your list n grows so much is that you have a double for-loop. To achieve your desired output you can just iterate through both lists at the same time using the zip function:

for k, v in zip(group1, group2):
    if k == v:
        a.append(k)
        print("a=",a)
    else:
        n.append(k)
        print("n=",n)

print(n) # [1, 2, 3, 4]
print(a) # [5]

Here are some approaches which all do the same in the end.

group1 = [1, 2, 3, 4, 5]
group2 = [9, 8, 7, 6, 5]

a=[]
n=[]


# option 1:
for value in group1:
    if value in group2:
        a.append(value)
    else:
        n.append(value)

# option 2
a = [x for x in group1 if x in group2]
n = [x for x in group1 if not x in group2]

# option 3
a = list(filter(lambda x: x in group2, group1))
n = list(filter(lambda x: x not in group2, group1))


print("a =", a)
# output: a = [5]
print("n =", n)
# output: n = [1, 2, 3, 4]

Hope this helps! Good luck and have fun learning python!

do a list comprehension and use in :

a = [x for x in group1 if x in group2]
#[5]

n = [x for x in group1 if x not in group2]
#[1, 2, 3, 4]

or faster:

n = [x for x in group1 if x not in a]
#[1, 2, 3, 4]

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