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

Python新手求助:如何将指定循环代码简化为列表推导式?

当然可以用列表推导式简化你的代码,下面是具体实现:

先修正个小细节:你的变量myList存的是字符串,不是列表,改成my_str会更准确,避免混淆。

方式一:先生成筛选后的列表,再打印(可读性更好)

my_str = " Bob said, breakthrough study reveals that human and octopus brains have common features"
# 用列表推导式筛选出首字母为"b"的单词
filtered_words = [word for word in my_str.split() if word[0] == "b"]
# 逐个打印结果
for word in filtered_words:
    print(word)

方式二:直接在列表推导式里执行打印(更紧凑,但可读性稍弱)

如果你想一步到位,也可以把打印操作放进列表推导式里:

my_str = " Bob said, breakthrough study reveals that human and octopus brains have common features"
[print(word) for word in my_str.split() if word[0] == "b"]

另外提个小建议:原代码只判断了小写"b",如果要忽略大小写(比如匹配开头是大写"B"的单词),可以把判断条件改成word[0].lower() == "b",这样Bob也会被筛选出来。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:55:17