如何在Python中通过索引从列表中删除n个元素?

时间:2012-03-02 05:28:03

标签: python list

让我们假设,

g = ['1', '', '2', '', '3', '', '4', '']

我想从g中删除所有'',我必须得到

g = ['1', '2', '3', '4']

4 个答案:

答案 0 :(得分:5)

>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> filter(None, g)
['1', '2', '3', '4']

Help on built-in function filter in module `__builtin__`:

filter(...)
filter(function or None, sequence) -> list, tuple, or string

   Return those items of sequence for which function(item) is true.  If
   function is None, return the items that are true.  If sequence is a tuple
   or string, return the same type, else return a list.

如果您愿意,也可以使用列表推导

>>> [x for x in g if x!=""]
['1', '2', '3', '4']

答案 1 :(得分:5)

如果您的列表是所有字符串,请在if语句中使用空序列为false的事实:

>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> [x for x in g if x]
['1', '2', '3', '4']

否则,请使用[x for x in g if x != '']

答案 2 :(得分:4)

new_g = [item for item in g if item != '']

答案 3 :(得分:0)

如果''始终且仅在偶数编号的索引处,那么这是一个实际删除项目的解决方案:

>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> g[::2]
['1', '2', '3', '4']
>>> g[1::2]
['', '', '', '']
>>> del g[1::2]  #  <-- magic happens here.
>>> g
['1', '2', '3', '4']

神奇的当然是 slice assignment.