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

标签 python python-2.7 lambda higher-order-functions

使用 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/

相关文章:

python - Pyinstaller 错误 ImportError : No module named 'requests. packages.chardet.sys

Java8 lambda 将 List 转换为 Map of Maps

Java 8 - 在 stream.map() 中链接构造函数调用和 setter

python - 尽管测试重试并返回 true,断言仍失败

c++ - 是否有可能创建一个仅是 lambda 的概念?

python - 如何在 django-tinymce 中启用插件?

python - Django 过滤器未返回正确的结果

python - 不同概率数据的平均值

python - 为字符串的长度创建一个变量是否更快?

python - 不确定如何从网络上抓取可能位于多个不同位置的特定值