刪除列表中的空元素
本以爲挺簡單的,一頓操作之後,再加上網上的資料,還有點小複雜。
以案例來說,更清晰些,做個學習筆記。
list_eg = ['',' ','hello','\n','world','\t']
print(list_eg)
輸出如下
['', ' ', 'hello', '\n', 'world', '\t']
在百度的時候發現一個大神寫的表達式
list_eg_change = [x.strip() for x in list_eg if x.strip()!='']
print(list_eg_change)
輸出如下
['hello', 'world']
看着有點傻眼,把這個三元表達式拆開,就看的清楚了。
list_eg = ['',' ','hello','\n','world','\t']
list_eg_change = []
for i in list_eg:
if i.strip() !='':
i = i.strip()
list_eg_change.append(i)
print(list_eg_change)
步驟是:
1、遍歷列表list_eg
,每個元素進行 i.strip()
刪除字符左右的空格。
2、如果i.strip()
不等於空值,則將i.strip()
賦值給i
。
3、列表list_eg_change.append()
得到想要的數據。