【问题标题】:Solved-Why aren't both consecutive for loops executed?已解决 - 为什么两个连续的 for 循环都不执行?
【发布时间】:2020-11-08 22:53:09
【问题描述】:

[初学者提醒] 我正在编写代码并记录它们的变化。我想将这个 for 循环的变体组合在一个文件中,但只执行第一个。为什么以及我必须做什么才能实现这一目标?

teams = ['Dragons', 'Wolves', 'Pandas', 'Unicorns']
n = 1

for home_team in teams:
    for away_team in teams[n:]:     # This block causes the execution to increase n by one
        if home_team != away_team:  # for every away_team in one home_team
            print(home_team, away_team)  # then proceeds to the next home_team
            n += 1

for home_team in teams:
    for away_team in teams[n:]:     # This block causes the execution to increase n by one
        if home_team != away_team:  # for every home_team
            print(home_team, away_team)
    n += 1

【问题讨论】:

  • 第二个循环开始时n 的值是多少?
  • 相同的值,我明白你的意思,谢谢!

标签: python order-of-execution nested-for-loop


【解决方案1】:

第二部分假设 n 的值自第一部分结束以来没有改变,导致执行不打印任何结果。 [由 Mark Meyer 暗示。]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多