简体   繁体   中英

Is there a pythonic way to iterate through the difference of two lists?

My goal is to iterate through the difference of two lists

I attempted a bodge code to write a - b as follows

for i in a:
        if i in b:
            continue
        #statements

I was wondering if there was a more pythonic/efficient way of doing this.

You could use sets , to look at the difference:

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

a = set(a)
b = set(b)

for i in a.difference(b):
    print(i)

# even supports the arithmetic syntax :D
for i in a - b:
    print(i)

What you have is fine. If you object to the continue statement, you can iterate over a generator:

for i in (x for x in a if x not in b):

though that is arguably worse in terms of readability.

In terms of sets, the items in a but not in b would be the set difference, therefore this would be

for i in set(a).difference(b):
    # statements

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