简体   繁体   中英

How can I compare two lists elements in Pyhton 3.8?

For example:

if two lists elements are

a = [1,2,3,4,5]
b = [2,3,4,5,6]

and I want to get [2,3,4,5] because its sharing the same number? Can somebody help me?

Oh, and by the way, how to wrote the code if the a and b is random list?

You can either use list comprehension or set union:

a = [1,2,3,4,5]
b = [2,3,4,5,6]

res = [x for x in a if x in b]
res_set = set(a) & set(b)

print(res)     # [2, 3, 4, 5]
print(res_set) # {2, 3, 4, 5}
a = [1,2,3,4,5]
b = [2,3,4,5,6]

c=[x for x in a if x in b]
d=[y for y in (a+b) if y not in c]

print(c)    # [2, 3, 4, 5]
print(d)    # [1,6]

You can get the same element and get different elements.

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