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']


沒有留言:

張貼留言

[ FP In Python ] Ch1. (Avoiding) Flow Control

Preface   In typical imperative Python programs—including those that make use of classes and methods to hold their imperative code—a block...