如何从列表中删除少于N个标记的字符串?

时间:2018-12-12 15:56:03

标签: python python-3.x

给出一个字符串列表,例如:

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:])

但是,它不起作用。关于如何删除令牌少于三个的所有字符串的任何想法

2 个答案:

答案 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)

这是使用filterlambda进行此操作的另一种方式:

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))