首页 > 解决方案 > 用字数替换较长的句子

问题描述

我试图弄清楚如何用字数替换更长的句子(5 个或更多单词)。

s = ['Two heads are better than one', 'Time flies', 'May the force be with you', 'I do', 'The Itchy and Scratchy Show', 'You know nothing Jon Snow', 'The cat ran']

如果我这样做:

numsentences = [len(sentence.split()) for sentence in s]

print(numsentences)

我得到字数。但我不知道如何让整个列表显示出 4 个或更少单词的句子出现的位置,而 5 个或更多单词的句子按字数打印。

然后我尝试了这样的事情:

sn = []
for sentence in s:
    num if len(sentence.split(i) > 2)

但我显然不在正确的轨道上。

我需要得到类似的东西:

s = [6, 'Time flies', 6, 'I do', 5, 5, 'The cat ran']

标签: pythonloopsfor-looplist-comprehension

解决方案


Using list comprehension:

output = [string if len(string.split(' ')) < 5 else len(string.split(' ')) for string in s]

Output:

[6, 'Time flies', 6, 'I do', 5, 5, 'The cat ran']

推荐阅读