2017年7月26日 星期三

[ Python 常見問題 ] Remove empty strings from a list of strings

Source From Here 
Question 
I want to remove all empty strings from a list of strings in python. Is there any more pythonic way to do this? 

How-To 
There are many approaches to fit your need: 
* Using Built-in Function - filter(function, iterable) 
>>> alist = ['This', '', 'is', '', 'for', 'testing', ''] 
>>> filter(lambda e: len(e) > 0, alist) // Filter out element with length > 1 
['This', 'is', 'for', 'testing']

Notes. Python 3 returns an iterator from filter, so should be wrapped in a call to list() 

* List Comprehensions 
>>> [ e for e in alist if e] 
['This', 'is', 'for', 'testing']


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...