简体   繁体   English

有没有一种pythonic方法来遍历两个列表的差异?

[英]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我尝试了一个 bodge 代码来编写 a - b 如下

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

I was wondering if there was a more pythonic/efficient way of doing this.我想知道是否有更pythonic/更有效的方法来做到这一点。

You could use sets , to look at the difference:您可以使用sets来查看差异:

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:如果你 object 到continue语句,你可以遍历一个生成器:

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就集合而言, a中但不在b中的项目将是集合差异,因此这将是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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