为什么 map 函数不 return 没有重复元素的列表?
Why the map function doesn't return the list without duplicate elements?
我有这个列表:
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
函数 returns 是 Python3 中的一个空列表?
因为在 python-3.x 中 map
不会立即计算 。它作为一个生成器工作,其中元素是根据需要动态生成的:这可以更有效,因为例如您可能只需要前三个元素那么为什么要计算所有元素?所以只要你不以某种方式具体化 map
的输出,你就没有真正计算出地图。
例如,您可以使用 list(..)
强制 Python 评估列表:
<b>list(</b>map(lambda x: not x in list2 and list2.append(x), list1)<b>)</b>
在这种情况下,python-3.x 将为 list2
生成相同的结果。
我有这个列表:
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
函数 returns 是 Python3 中的一个空列表?
因为在 python-3.x 中 map
不会立即计算 。它作为一个生成器工作,其中元素是根据需要动态生成的:这可以更有效,因为例如您可能只需要前三个元素那么为什么要计算所有元素?所以只要你不以某种方式具体化 map
的输出,你就没有真正计算出地图。
例如,您可以使用 list(..)
强制 Python 评估列表:
<b>list(</b>map(lambda x: not x in list2 and list2.append(x), list1)<b>)</b>
在这种情况下,python-3.x 将为 list2
生成相同的结果。