[英]How to remove items with whitespace in array
我有一個由項目組成的列表,其中一些項目只有一個空格,我想完全刪除。 這究竟是如何有效地完成的?
aList = [u'This is a test', u' ', u'Something', u' ', u'Something more', u' ', u'Another test', u' ', u' Test test']
因此,所有帶有u' '
的項目都必須從列表中完全刪除。
使用帶有string.strip()
的列表理解:
>>> l = [u'This is a test', u' ', u'Something', u' ', u'Something more', u' ', u'Another test', u' ', u' Test test']
>>> sans_whitespace = [s for s in l if s.strip()]
>>> sans_whitespace
[u'This is a test', u'Something', u'Something more', u'Another test', u' Test test']
最簡單的方法可能是使用列表推導過濾掉只有空格的字符串。
您可以使用isspace()
檢查字符串是否完全由一個或多個空格組成:
>>> [x for x in aList if not x.isspace()]
['This is a test', 'Something', 'Something more', 'Another test', ' Test test']
結果=np.char.replace(結果," ","io")
結果=np.char.replace(結果,"io","")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.