group = 0
position = 0
end = "n"
while (end == "n"):
group = group + 1
xy = [[] for xy in range(group)]
xy[position].append(int(input("Input x value: ")))
xy[position].append(int(input("Input y value: ")))
position = position + 1
end = input("Last entries? [y/n] ")
print (xy)
输出
Input x value: 1
Input y value: 2
Last entries? [y/n] n
Input x value: 3
Input y value: 4
Last entries? [y/n] y
[[], [3, 4]]
我的第一个列表丢失了,我不明白为什么。怎么解决这个问题?
最佳答案
发生这种情况是因为您每次循环都运行此行:
xy = [[] for xy in range(group)]
这会将 xy
重新分配给空列表的列表。
考虑以下代码,它可以简化您现有的工作:
end = "n"
xy = []
while (end == "n"):
xy.append([int(input("Input x value: ")), int(input("Input y value: "))])
end = input("Last entries? [y/n] ")
print (xy)
关于python - 嵌套列表代码中缺少第一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59844834/