[英]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/更有效的方法来做到这一点。
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.