You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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']
result = [len(sentence.split()) if len(sentence.split()) >= 5 else sentence for sentence in s]
print(result)

如果你更习惯用循环写法,可读性更高的版本如下:

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']
sn = []
for sentence in s:
    word_cnt = len(sentence.split())
    if word_cnt >= 5:
        sn.append(word_cnt)
    else:
        sn.append(sentence)
print(sn)
原有代码问题说明

你之前写的循环存在以下错误:

  • 语法不完整,if 判断没有对应的执行分支和else分支
  • sentence.split(i)写法错误,变量i没有定义,按空格拆分直接调用split()即可
  • 判断条件错误,你需求里的阈值是单词数≥5,不是大于2

两种写法运行后都会输出你预期的结果:[6, 'Time flies', 6, 'I do', 5, 5, 'The cat ran']

内容的提问来源于stack exchange,提问作者Noob3000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 19:15:00