【问题标题】:Why the map function doesn't return the list without duplicate elements?为什么 map 函数不返回没有重复元素的列表?
【发布时间】:2017-02-04 17:02:57
【问题描述】:

我有这个清单:

list1 = [1, 1, 1, 3, 3, 3, 56, 6, 6, 6, 7]

我想摆脱重复值。 map 函数的代码取自 here。 这是完整的测试代码:

list1 = [1, 1, 1, 3, 3, 3, 56, 6, 6, 6, 7]

list2 = []
map(lambda x: not x in list2 and list2.append(x), list1)
print(list2)

list2 = []
[list2.append(c) for c in list1 if c not in list2]
print(list2)

list2 = []

for c in list1:
    if c not in list2:
        list2.append(c)

print(list2)

在 Python 2.7 中是打印:

[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]

在 Python 3.4 中,它会打印:

[]
[1, 3, 56, 6, 7]
[1, 3, 56, 6, 7]

为什么map 函数在 Python3 中返回一个空列表?

【问题讨论】:

  • 你为什么不用np.unique
  • 因为这不是生产代码,所以仅供学习使用:)

标签: python-2.7 list python-3.4


【解决方案1】:

因为在 map不会立即评估。它作为生成器工作,根据需要动态生成元素:这可能更有效,因为您可能只需要前三个元素,那么为什么要计算所有元素?因此,只要您不以某种方式具体化map 的输出,您就没有真正计算出地图。

例如,您可以使用 list(..) 强制 Python 评估列表:

<b>list(</b>map(lambda x: not x in list2 and list2.append(x), list1)<b>)</b>

在这种情况下, 将为list2 生成相同的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 2021-06-05
    • 2021-05-23
    • 2013-05-09
    • 1970-01-01
    • 2020-09-23
    相关资源
    最近更新 更多