讓我們假設,如何通過Python中的索引從列表中刪除n個元素?
g = ['1', '', '2', '', '3', '', '4', '']
我想刪除所有''
從克,在那裏我得到
g = ['1', '2', '3', '4']
讓我們假設,如何通過Python中的索引從列表中刪除n個元素?
g = ['1', '', '2', '', '3', '', '4', '']
我想刪除所有''
從克,在那裏我得到
g = ['1', '2', '3', '4']
如果'總是隻有在偶數索引處,這裏是一個解決方案,實際上刪除了這些項目:
>>> 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']
ma當然是一個slice assignment.
>>> 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']
new_g = [item for item in g if item != '']
如果你的列表中的所有字符串,使用的事實,空序列爲假的if語句:
>>> g = ['1', '', '2', '', '3', '', '4', '']
>>> [x for x in g if x]
['1', '2', '3', '4']
否則,使用[x for x in g if x != '']
這是最Pythonic的解決方案。 – 2012-03-02 05:32:12
作爲一個方面說明,''過濾器'與'None'刪除* falsy *的任何值。例如'filter(None,[False,0,1,2,3])'''''1,2,3]' – 2012-03-02 05:32:58
不同意'最Pythonic'。 Guido van Rossum談到過濾器:「列表理解能夠更好地完成同樣的事情」。請參見[python regrets]的幻燈片4(http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf) – wim 2012-03-02 05:35:07