如何从下面的列表中删除333的两次出现?
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]我在Python2.7命令行中输入了以下脚本
for num in a:
if num == 333:
a.remove(num)但只有333的第一次出现被删除。
>>> a
[-1, 1, 66.25, 333, 1234.5]如何删除同一元素的所有出现?我希望能够指定要删除所有事件的元素,并按相同的名称获得一个新列表。
发布于 2013-09-05 06:14:41
在这里使用列表理解:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> [item for item in a if item != 333]
[-1, 1, 66.25, 1234.5]您的方法不起作用是因为you're modifying a list while iterating over it。
for num in a[:]: #iterate over a shallow copy
if num == 333:
a.remove(num)若要获取唯一项的列表,请使用一组:
>>> seen = set()
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> [item for item in a if item not in seen and not seen.add(item)]
[-1, 1, 66.25, 333, 1234.5]如果秩序不重要:
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> list(set(a))
[66.25, 1, 333, -1, 1234.5]发布于 2013-09-05 06:26:27
我觉得你想要的是这样的
a = [-1, 1, 66.25, 333, 333, 1234.5]
a = [el for el, count in collections.Counter(a).items() if count == 1]这将从任何值的列表中删除元素,条件是它们不止一次出现。
发布于 2013-09-05 06:58:48
在下面的代码中,从5,3,4,7,8,4列表中删除了4编号
>>> def pp(x):
... if x==4:
... return False
... else:
... return True
...
>>> filter(pp, [5,3,4,7,8,4])输出
[5, 3, 7, 8]https://stackoverflow.com/questions/18628973
复制相似问题