![](/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.