我正在试图找出如何用字数替换较长的句子(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']
使用列表理解:
输出:
我可能会通过创建两个列表来实现这一点
首先创建字数列表,然后使用
zip
同时遍历句子和字数。您可以根据您的条件从一个列表或另一个列表中选择包含该值您可以使用map()从每个句子中提取字数,使用zip()将这些字数(
n
)与原始字符串(o
)组合起来,然后在列表中选择两者:相关问题 更多 >
编程相关推荐