【问题标题】:why is a for loop not appending a list为什么for循环不附加列表
【发布时间】:2018-12-18 04:03:09
【问题描述】:

在下面的代码中,循环似乎不起作用。

powers = []
x = 0
y = 0
z = 1

for x in powers:
powers.append([])
for y in powers[x]:
    powers[x].append(z ** y)
    z = z + 1
    if z < 1001:
        continue
    else:
        break
x = x + 1
y = y + 1
z = 1
print(powers)

但是,当我在终端中运行它时,它只会返回一个空的权力列表。它不显示错误消息。

请帮忙。

【问题讨论】:

  • 请先纠正for 循环的缩进。注意for x in powerspowers = []),什么都不做。请提供minimal reproducible example
  • for y in powers[x]。这一行肯定会给你一个错误。
  • 从未听说过调试器?我强烈建议您使用其中之一来了解您的问题所在
  • 另外:甚至不清楚您的预期输出是什么

标签: python list loops


【解决方案1】:

您的代码格式错误,所以请考虑格式化,反正您的一些错误是代码cmets。

powers = []
x = 0
y = 0
z = 1

for x in powers: #here you're overriding former declaration of x, also powers is empty so for doesn't have a single run
powers.append([]) ##code is not indented so this istruction execute only once
for y in powers[x]: ##powers[x] is an empty list
        powers[x].append(z ** y)
        z = z + 1
        if z < 1001:
            continue
        else:
            break
z = 1 ## this is outside the cycle 
x = x + 1 
y = y + 1 

print(powers)

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 2012-05-20
    • 2020-03-26
    • 2019-11-03
    • 2019-07-12
    • 1970-01-01
    • 2021-08-15
    • 2020-09-25
    • 2018-10-11
    相关资源
    最近更新 更多