![](/img/trans.png)
[英]More pythonic way to iterate through two lists switching directions after every line?
[英]Is there a pythonic way to iterate through the difference of two lists?
我的目标是遍历两个列表的差异
我尝试了一个 bodge 代码来编写 a - b 如下
for i in a:
if i in b:
continue
#statements
我想知道是否有更pythonic/更有效的方法来做到这一点。
您可以使用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)
你所拥有的很好。 如果你 object 到continue
语句,你可以遍历一个生成器:
for i in (x for x in a if x not in b):
尽管就可读性而言,这可以说是更糟。
就集合而言, a
中但不在b
中的项目将是集合差异,因此这将是
for i in set(a).difference(b):
# statements
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.