嵌套列表代码中缺少第一个列表
First list is missing in nested list code
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)
你每次都在重新定义列表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)
使用此代码,您甚至不需要使用 group
和 position
变量。
您可以进一步简化它,但可读性较差:
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)
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)
你每次都在重新定义列表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)
使用此代码,您甚至不需要使用 group
和 position
变量。
您可以进一步简化它,但可读性较差:
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)