【问题标题】:Why for loop does do this with 2d list?为什么 for 循环会使用 2d 列表执行此操作?
【发布时间】:2022-07-22 17:27:51
【问题描述】:

我正在编写一些重复相同文本但有变体的代码,但我遇到了问题。

这里有一些代码

tick = int(input("Start: "))
end = False
listname = []

while not end:
    a = input()
    if a == "skip":
        tick += 1
    elif a == "end":
        end = True
    else:
        listname.append([tick, a])
        tick += 1

for b in listname:
    print(str(b[0]) + " something " + b[1])

我输入:

Start: 10
1
2
3
4
5
end

然后打印出来:

10 something
11 something 1
12 something
13 something 2
14 something
15 something 3
16 something 
17 something 4
18 something
19 something 5
20 something

但我期待:

10 something 1
11 something 2
12 something 3
13 something 4
14 something 5

为什么会这样?

【问题讨论】:

  • 无法复制。

标签: python


【解决方案1】:

您的控制语句中需要tick+=1 before listname.append([tick,a])。这将导致 a 在添加到数组之前为 1。

【讨论】:

  • 不。他们想从 10 点开始。
猜你喜欢
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多