2

由于存在一些行为差异map(尤其是 Python 2 和 Python 之间的三个参数 - Python 2 vs Python 3 - 三个参数的映射行为差异?),我试图通过使用来“安全”,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行为有这样的原因吗?这是一个错误吗?


看起来在使用源代码注释中提到的模块获取 Python 2map行为时存在一些问题。past.builtins

4

1 回答 1

2

这是他们实施的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那么这些对象将被“解包”并返回一个扁平列表。我不确定这是从哪里来的,因为据我所知,Python 2 没有这样做,即使对于元组:

# Python 2
print(map(lambda x: (x,), [1, 2]))
# [(1,), (2,)]

如果您想继续关注,库代码存储库中似乎有一个未解决的问题。

于 2020-03-12T13:21:29.933 回答