[英]Why does past.builtins map behave wrongly?
由於map
存在一些行為差異(尤其是 Python 2 和 Python 之間的三個參數 - Python 2 vs Python 3 - 三個參數的地圖行為差異? ),我試圖通過使用from past.builtins import map
來“安全” from past.builtins import 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
行為時存在一些問題。
這是他們實現map
的錯誤。 這是他們的代碼:
def oldmap(func, *iterables):
"""
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(*iterables)
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
在它們的實現中,如果可調用對象返回一個len
為 1 的對象列表,那么這些對象將被“解包”並返回一個扁平化的列表。 我不確定這是從哪里來的,因為據我所知,Python 2 沒有這樣做,即使是元組:
# Python 2
print(map(lambda x: (x,), [1, 2]))
# [(1,), (2,)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.