python - Python 2 vs Python 3 - 三个参数的地图行为差异?
问题描述
以下代码在 Python 2 和 Python 3 中的行为不同:
all(map(lambda x,y: x, [1, 2], [1, 2, 3]))
Python 2 提供False
,而 Python 3 提供True
. Python 2的文档None
说,如果较短的列表用完,它将提供,但 Python 3不这样做。
我正在编写一个出于某种原因确实需要维护长度的代码。获得旧行为的最干净的方法是什么?我知道我可以使用from past.builtin import map as old_map
,但是是否有更优雅的解决方案可以在两个版本中使用?
解决方案
本质上,map
参数的多个迭代将zip
迭代,然后使用zip
as var-args 中的元组调用函数。itertools.starmap
因此,您可以使用and获得相同的行为zip
:
>>> a = [10, 20]
>>> b = [1, 2, 3]
>>> f = lambda x, y: x
>>> list(map(f, a, b))
[10, 20]
>>> from itertools import starmap
>>> list(starmap(f, zip(a, b)))
[10, 20]
然后可以通过替换来实现您想要的zip
行为itertools.zip_longest
:
>>> from itertools import starmap, zip_longest
>>> list(starmap(f, zip_longest(a, b)))
[10, 20, None]
itertools
Python 2 中也存在这两个函数,除了第二个被命名izip_longest
。你可以import ... as ...
解决这个问题。
推荐阅读
- c++ - 找到两个分段线性函数的交集
- c# - 我如何操作 NLog 的堆栈级别?
- jquery - 打开页面时在 symfony 中加载微调器
- python - 将具有多个值的字符串转换为字典?
- javascript - React - 面试练习
- dart - 在 Dart 中将对象推入数组
- wordpress - 我需要运行一个使用 sftp 放置在 AWS 服务器上的文件
- python - 当在多对多模型中创建新的目标实例时,更新源模型的每个实例的推荐方法是什么?
- javascript - 将日期格式化为用户在输入中输入的 dd/mm/yyyy
- javascript - 如何在Javascript中创建具有随机x和y坐标的对象列表?