Python 删除不改变的列表元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25004347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove list element without mutation
提问by user3457749
Assume you have a list
假设你有一个列表
>>> m = ['a','b','c']
I'd like to make a new list nthat has everything except for a given item in m(for example the item 'a'). However, when I use
我想创建一个新列表n,其中包含除给定项目之外的所有内容m(例如 item 'a')。但是,当我使用
>>> m.remove('a')
>>> m
m = ['b', 'c']
the original list is mutated (the value 'a'is removed from the original list). Is there a way to get a new list sans-'a'without mutating the original? So I mean that mshould still be [ 'a', 'b', 'c' ], and I will get a newlist, which has to be [ 'b', 'c' ].
原始列表发生变异(该值'a'从原始列表中删除)。有没有办法在'a'不改变原始列表的情况下获得新列表?所以我的意思是m应该仍然是[ 'a', 'b', 'c' ],我会得到一个新的列表,它必须是[ 'b', 'c' ].
采纳答案by Krumelur
I assume you mean that you want to create a new list without a given element, instead of changing the original list. One way is to use a list comprehension:
我假设您的意思是要创建一个没有给定元素的新列表,而不是更改原始列表。一种方法是使用列表理解:
m = ['a', 'b', 'c']
n = [x for x in m if x != 'a']
nis now a copy of m, but without the 'a'element.
n现在是 的副本m,但没有'a'元素。
Another way would of course be to copy the list first
另一种方法当然是先复制列表
m = ['a', 'b', 'c']
n = m[:]
n.remove('a')
If removing a value by index, it is even simpler
如果通过索引删除一个值,那就更简单了
n = m[:index] + m[index+1:]
回答by Andrew Johnson
You can create a new list without the offending element with a list-comprehension. This will preserve the value of the original list.
您可以使用列表理解创建一个没有违规元素的新列表。这将保留原始列表的值。
l = ['a','b','c']
[s for s in l if s!='a']
回答by Amen
Another approach to list comprehension is numpy:
列表理解的另一种方法是 numpy:
>>> import numpy
>>> a = [1, 2, 3, 4]
>>> list(numpy.remove(a,a.index(3)))
[1, 2, 4]
回答by u10412558
There is a simple way to do that using built-in function :filter .
使用内置函数 :filter 有一种简单的方法可以做到这一点。
Here is ax example:
这是斧头的例子:
a = [1, 2, 3, 4]
b = filter(lambda x: x != 3,a)
回答by Oleg O
If the order is unimportant, you can use set (besides, the removal seems to be fast in sets):
如果顺序不重要,则可以使用 set (此外,set 中的删除似乎很快):
list(set(m) - set(['a']))

