python - 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
?什么是a
和b
在这种情况下?它们是如何加在一起的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
推荐阅读
- java - 如何从 JSON API 过滤数据
- javascript - 选择语言后只显示一个问题,不显示其他选项
- python - 从字典中查找最小值(不包括 0)
- python - 如何在 Django 中更改 models.ForeignKey 的输出?
- sql - 如何在存储过程选择子句中使用 with 子句 CTE 表达式常见
- git - 当我和同事在同一个分支上工作时
- javascript - 我无法使用 JS 代码设置上传的宽度/高度
- google-chrome - 无法在 Chrome / Edge 中打开 PowerApps
- php - 在laravel中使用vue-router时无法获取url
- java - 如何从 mac OS Big Sur 中删除多个 java 版本?