從字符串列表中刪除空字符串

我想從python中的字符串列表中刪除全部空字符串。 python

個人想法以下: spa

while '' in str_list:
    str_list.remove('')

有沒有更多的Python方式能夠作到這一點? code


#1樓

代替if x,我將使用if X!=」來消除空字符串。 像這樣: rem

str_list = [x for x in str_list if x != '']

這將在列表中保留「無」數據類型。 另外,若是您的列表包含整數,而且0是其中的一個,那麼它也會被保留。 字符串

例如, get

str_list = [None, '', 0, "Hi", '', "Hello"]
[x for x in str_list if x != '']
[None, 0, "Hi", "Hello"]

#2樓

>>> lstr = ['hello', '', ' ', 'world', ' ']
>>> lstr
['hello', '', ' ', 'world', ' ']

>>> ' '.join(lstr).split()
['hello', 'world']

>>> filter(None, lstr)
['hello', ' ', 'world', ' ']

比較時間 string

>>> from timeit import timeit
>>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
4.226747989654541
>>> timeit('filter(None, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
3.0278358459472656

請注意, filter(None, lstr)不會刪除空字符串用空格' ' ,它只是修剪掉'' ,而' '.join(lstr).split()將同時刪除。 it

要使用filter()除去空格字符串,須要花費更多時間: io

>>> timeit('filter(None, [l.replace(" ", "") for l in lstr])', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
18.101892948150635

#3樓

str_list = ['2', '', '2', '', '2', '', '2', '', '2', '']

for item in str_list:
    if len(item) < 1:  
        str_list.remove(item)

簡短而甜美。 import


#4樓

filter(None, str)不會刪除空格爲''的空字符串,它只會刪除'和''。

join(str).split()刪除二者。 可是,若是您的list元素有空間,那麼它將更改您的list元素,由於它首先鏈接了list的全部元素,而後按空格將它們吐出來,所以您應該使用:-

str = ['hello', '', ' ', 'world', ' ']
print filter(lambda x:x != '', filter(lambda x:x != ' ', str))

它會同時刪除這兩個元素,而且不會影響您的元素,例如:-

str = ['hello', '', ' ', 'world ram', ' ']
print  ' '.join(lstr).split()
print filter(lambda x:x != '', filter(lambda x:x != ' ', lstr))

輸出:-

['hello','world','ram'] <--------------輸出' '.join(lstr).split()
['hello','world ram']


#5樓

清單理解

strings = ["first", "", "second"]
[x for x in strings if x]

輸出: ['first', 'second']

相關文章
相關標籤/搜索