首页 > 解决方案 > 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 未定义,但正在比较?它是否也通过“a”循环b for a?什么是ab在这种情况下?它们是如何加在一起的sum()?正在循环什么?如果我能帮助理解这一点,将不胜感激。

提前致谢!

标签: pythonloopssumzip

解决方案


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

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(), 和列表推导之类的东西,尽管对于许多人来说,当你看到它们在行动中时它更有意义。


推荐阅读