python - 用字数替换较长的句子
问题描述
我试图弄清楚如何用字数替换更长的句子(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']
解决方案
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']
推荐阅读
- apache-spark - 带变量的 SQL 编译语句的 SparkSQL 等效项
- wpf - 列数据模板内的复选框数据上下文问题
- javascript - 使用jquery删除动态元素
- node.js - Node Js Web socket客户端停止监听
- extjs - extjs 的日期范围选择器?
- django - Django celery beat scheduler 在亚洲/加尔各答时区不起作用
- java - 在事件被持久化后执行副作用
- shopify - 使用 shopify 和 Liquid 在产品图片的右上角添加一个小徽标
- html - 嵌入 Facebook 视频在智能手机上播放质量低
- python - 如何强制 pytz 使用当前的标准时区?