![](/img/trans.png)
[英]Remove from a list of strings, those strings that have only empty spaces or that are made up of less than 3 alphanumeric characters
[英]How to remove from a list the strings that have less than N tokens?
給出一個字符串列表,說:
a = ['hey','hey how are you','good how are you','I am', 'I am fine 8998','9809 908']
如何刪除少於三個令牌的字符串?:
a = ['hey how are you','good how are you', 'I am fine 8998']
我試過了:
' '.join(a.split(' ')[3:])
但是,它不起作用。 知道如何刪除少於三個令牌的所有字符串
你可以使用這個列表理解:
>>> [i for i in a if len(i.split())>=3]
['hey how are you', 'good how are you', 'I am fine 8998']
這是使用filter
和lambda
執行相同操作的另一種方法:
a = ['hey','hey how are you','good how are you','I am', 'I am fine 8998','9809 908']
res = list(filter(lambda x: x.count(' ') >= 2, a))
# ['hey how are you', 'good how are you', 'I am fine 8998']
要么:
res = list(filter(lambda x: len(x.split()) >= 3, a))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.