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


沒有留言:

張貼留言

[ Python 文章收集 ] SQLAlchemy quick start with PostgreSQL

Source From   Here   Preface   This is a quick tutorial for getting started with   SQLAlchemy Core API .   Prerequisites   In this quick st...