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

Python循环中print重复执行问题:如何让指定内容仅打印一次?

解决方法

你的问题核心是缩进错误,导致目标语句被包含在循环体内重复执行。

先看你的原代码:

requested_trades = ['long only', 'short only', 'neutral position']
for requested_trade in requested_trades:
  print(f"My Trade List: {requested_trade}.")

  print("\nExecute them well")

print("\nExecute them well")和循环内的打印语句缩进相同,意味着它是循环的一部分,每遍历一个列表元素就会执行一次。

修改方式很简单,把这句代码的缩进移除,放到for循环的外面:

requested_trades = ['long only', 'short only', 'neutral position']
for requested_trade in requested_trades:
  print(f"My Trade List: {requested_trade}.")

print("\nExecute them well")

调整后,循环会先完整输出所有交易条目,之后才执行一次print("\nExecute them well"),完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 06:12:09