给出一个字符串列表,例如:
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:])
但是,它不起作用。关于如何删除令牌少于三个的所有字符串的任何想法
答案 0 :(得分:7)
您可以使用此列表理解:
>>> [i for i in a if len(i.split())>=3]
['hey how are you', 'good how are you', 'I am fine 8998']
答案 1 :(得分:6)
这是使用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))