Python 如何使用列表理解根据字长筛选字符串列表?
我正在尝试筛选字符串列表中等于1个字符或2个字符的单词。这是我的样本数据-Python 如何使用列表理解根据字长筛选字符串列表?,python,list-comprehension,Python,List Comprehension,我正在尝试筛选字符串列表中等于1个字符或2个字符的单词。这是我的样本数据- l = ['new vaccine tech long term testing', 'concerned past negative effects vaccines flu shot b', 'standard initial screening tb never tb chest x ray'] 我试着写这个逻辑,但不知怎么的,输出结果是一个单词列表,而不是句子列表 cleaner = [ ''.
l = ['new vaccine tech long term testing',
'concerned past negative effects vaccines flu shot b',
'standard initial screening tb never tb chest x ray']
我试着写这个逻辑,但不知怎么的,输出结果是一个单词列表,而不是句子列表
cleaner = [ ''.join(word) for each in l for word in each.split() if len(word) > 2 ]
cleaner
['new',
'vaccine',
'tech',
'long',
'term',
'testing',
'concerned',
'past',
'negative',
'effects',
'vaccines',
'flu',
'shot',
'standard',
'initial',
'screening',
'never',
'chest',
'ray']
如何使其输出如下
output = ['new vaccine tech long term testing',
'concerned past negative effects vaccines flu shot',
'standard initial screening never chest ray']
您需要使用嵌套列表理解,而不是单个列表理解。外层是句子,内层是单词
output = [' '.join([word for word in sentence.split() if len(word) > 2]) for sentence in l]
你需要用空格连接,而不是空字符串,在单词之间加空格
output = [' '.join([word for word in sentence.split() if len(word) > 2]) for sentence in l]
您需要使用嵌套列表理解,而不是单个列表理解。外层是句子,内层是单词
output = [' '.join([word for word in sentence.split() if len(word) > 2]) for sentence in l]
你需要用空格连接,而不是空字符串,在单词之间加空格
output = [' '.join([word for word in sentence.split() if len(word) > 2]) for sentence in l]
您可以进行筛选以获得字符串的特定大小的单词,然后将其加入到列表中
l = ['new vaccine tech long term testing',
'concerned past negative effects vaccines flu shot b',
'standard initial screening tb never tb chest x ray']
res = [" ".join(filter(lambda x: len(x) > 2, eaach.split(' '))) for eaach in l]
print(res)
您可以进行筛选以获得字符串的特定大小的单词,然后将其加入到列表中
l = ['new vaccine tech long term testing',
'concerned past negative effects vaccines flu shot b',
'standard initial screening tb never tb chest x ray']
res = [" ".join(filter(lambda x: len(x) > 2, eaach.split(' '))) for eaach in l]
print(res)