由于map中有一些行为差异(特别是在Python 2和Python之间有三个参数-Python 2与Python 3-具有三个参数时地图行为有差异吗?),我试图通过使用过去的来保证“安全” .builtins导入map
,以便我的功能完好无损。但这似乎不是吗?
这是Python 2代码:
map(lambda x: [x], [1, 2])
这使:
[[1], [2]]
这是我期望以相同的方式运行的Python 3代码,但不会:
from past.builtins import map
map(lambda x: [x], [1, 2])
给出:
[1, 2]
令人惊讶的是,新的map
可以按预期工作:
from builtins import map # Not needed if you didn't evaluate the above code.
list(map(lambda x: [x], [1, 2]))
为什么past.builtins
的map
会这样?这是一个错误吗?
*看起来像使用源代码注释中提到的past.builtins模块来获取Python 2
map`行为时存在一些问题。
问题来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
这是他们实施map
的错误。这是他们的代码:
def oldmap(func, \*terables):
"""
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the
items of the argument sequence(s). If more than one sequence is
given, the function is called with an argument list consisting of
the corresponding item of each sequence, substituting None for
missing values when not all sequences have the same length. If
the function is None, return a list of the items of the sequence
(or a list of tuples if more than one sequence).
Test cases:
>>> oldmap(None, 'hello world')
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> oldmap(None, range(4))
[0, 1, 2, 3]
More test cases are in past.tests.test_builtins.
"""
zipped = itertools.zip_longest(\*terables)
l = list(zipped)
if len(l) == 0:
return []
if func is None:
result = l
else:
result = list(starmap(func, l))
# Inspect to see whether it's a simple sequence of tuples
try:
if max([len(item) for item in result]) == 1:
return list(chain.from_iterable(result))
# return list(flatmap(func, result))
except TypeError as e:
# Simple objects like ints have no len()
pass
return result
错误的地方是:
# Inspect to see whether it's a simple sequence of tuples
在其实现中,如果callable返回一个len值为1的对象列表,则将这些对象“解压缩”并返回一个扁平列表。我不确定这是哪里来的,因为据我所知,Python 2甚至对于元组都没有这样做:
# Python 2
print(map(lambda x: (x,), [1, 2]))
# [(1,), (2,)]
如果您想继续,那么在库代码存储库中似乎存在一个未解决的问题。
回答来源:stackoverflow