Python 中循环解释的链式比较

Chained Comparison with Loop Explanation in Python

这里是初学者!我遇到了一些关于 zip() 函数与 sum() 函数组合的 python 代码,但这些代码对我来说没有意义,我想知道是否可以得到解释:

list_1 = ['a', 'a', 'a', 'b']
list_2 = ['a', 'b', 'b', 'b', 'c']

print(sum(a != b for a, b in zip(list_1, list_2)))

a和b没有定义,但是正在比较?它是否也通过 b for a 循环遍历“a”?在这种情况下,ab 是什么?它们如何与 sum() 一起添加?正在循环什么?如果能对我的理解有所帮助,将不胜感激。

提前致谢!

当遇到这样的代码时,将其分成小块并查看每个块的作用会很有帮助。这是一个注释版本:

list_1 = ['a', 'a', 'a', 'b']
list_2 = ['a', 'b', 'b', 'b', 'c']

print(list(zip(list_1, list_2))) # you need to pass this to  list() because zip is a lazy iterator
# correponding pairs from each list
# zip() trucates to the shortest list, so `c` is ignored
# [('a', 'a'), ('a', 'b'), ('a', 'b'), ('b', 'b')]

print([(a, b) for a, b in zip(list_1, list_2)])
# same thing as above using a list comprehension
# loops over each pair in the zip and makes a tuple of (a,b)

print([a != b for a, b in zip(list_1, list_2)])
# [False, True, True, False]
# compare each item in those pairs. Are they different?

print(sum(a != b for a, b in zip(list_1, list_2)))
# 2 
# take advantage of the fact that True = 1 and False = 0
# and sum those up -> 0 + 1 + 1 + 0

它也有助于查找诸如 zip(), and list comprehensions 之类的内容,尽管对于许多人来说,当您看到它们的实际效果时更有意义。

代码中的for结构是一个生成器。这种形式的生成器通常出现在列表理解中,但它也可以直接传递给需要迭代的函数,例如 sum.

如果你想看看生成器实际产生了什么,你可以这样做:

x = [a != b for a, b in zip(list_1, list_2)]

这相当于:

x = list(a != b for a, b in zip(list_1, list_2))

列表 x 中的值是 bool 值,其中 True 两个列表中的值比较不相等,而 False 它们比较相等。如果一个列表比另一个长,则跳过较短列表之后的值。

回到您的代码,它没有创建列表,而是作为生成器并直接传递给 sum,它将对任何可迭代对象进行操作。由于 bool 值只是整数(False = 0True = 1),这只是对两个列表之间不同值的数量求和(忽略较长列表中的额外值)。