Python 中的 filter、map 和 reduce 是否创建列表的新副本?

Does filter,map, and reduce in Python create a new copy of list?

使用Python 2.7。假设我们有 list_of_nums = [1,2,2,3,4,5] 我们想删除所有出现的 2。我们可以通过 list_of_nums[:] = filter(lambda x: x! = 2, list_of_nums)list_of_nums = filter(lambda x: x! = 2, list_of_nums).

这是 "in-place" 替换吗?另外,我们在使用过滤器时是否正在创建列表的副本?

list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)

list_of_nums = filter(lambda x: x != 2, list_of_nums)

是两个不同的操作,最终大多数相同的结果。

在这两种情况下,

filter(lambda x: x != 2, list_of_nums)

returns 要么是包含与过滤器匹配的项目的新列表(在 Python 2 中),要么是 list_of_nums 上的可迭代 returns 相同的项目(在Python 3).

第一种情况,

list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)

然后删除 list_of_nums 中的所有项,并用新列表或可迭代项中的项替换它们。

第二种情况,

list_of_nums = filter(lambda x: x != 2, list_of_nums)

将新列表分配给变量 list_of_nums

这会产生影响的时间是:

def processItemsNotTwo_case1(list_of_nums):
    list_of_nums[:] = filter(lambda x: x != 2, list_of_nums)
    # do stuff here
    # return something

def processItemsNotTwo_case2(list_of_nums):
    list_of_nums = filter(lambda x: x != 2, list_of_nums)
    # do stuff here
    # return something

list1 = [1,2,2,3,4,5]
processItemsNotTwo_case1(list1)
list2 = [1,2,2,3,4,5]
processItemsNotTwo_case2(list2)

使用此代码,list1 以新内容 [1,3,4,5] 结束,而 list2 以原始内容 [1,2,2,3,4,5] 结束。