繁体   English   中英

为什么 past.builtins 地图行为错误?

[英]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.builtinsmap表现得像这样有什么原因吗? 这是一个错误吗?


看起来在使用源代码注释中提到的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM