嵌套列表代码中缺少第一个列表

问题描述 投票:1回答:2
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]]

我的第一个清单不见了,我不明白为什么。该如何解决?

python-3.x nested-lists
2个回答
1
投票

之所以发生这种情况,是因为您在每个循环中都运行此行:

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)

1
投票

您每次都在xy中重新定义列表,因此所有列表都将被删除,仅最后一个将被保存。

下面是对其进行了一些编辑的代码:

end = "n"
xy = []

while (end == "n"):
    a = int(input("Input x value: "))
    b = int(input("Input y value: "))
    xy.append([a,b])
    end = input("Last entries? [y/n] ")

print (xy)

使用此代码,您甚至不需要使用groupposition变量。

您可以简化它,但可读性较低:

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)
© www.soinside.com 2019 - 2024. All rights reserved.