使用 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)
。
这是“就地”替换吗?此外,我们是否在使用过滤器时创建列表的副本?
最佳答案
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)
返回包含与过滤器匹配的项目的新列表(在 Python 2 中),或返回相同项目的可迭代 list_of_nums
(在 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]
。
关于python - Python 中的 filter、map 和 reduce 是否创建列表的新副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39308479/