Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 嵌套列表代码中缺少第一个列表_Python_Python 3.x_List_While Loop_Nested Lists - Fatal编程技术网

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

Python 嵌套列表代码中缺少第一个列表,python,python-3.x,list,while-loop,nested-lists,Python,Python 3.x,List,While Loop,Nested Lists,输出 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

输出

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
重新分配给空列表列表

考虑以下代码,它简化了您现有的工作:

xy = [[] for xy in range(group)]

每次重新定义列表xy时,将删除所有列表,只保存最后一个列表

以下是为使其正常工作而编辑的代码:

end=“n”
xy=[]
而(结束=“n”):
a=int(输入(“输入x值:”)
b=int(输入(“输入y值:”)
xy.append([a,b])
结束=输入(“最后输入?[y/n]”)
打印(xy)
使用此代码,您甚至不需要使用
group
position
变量

您可以进一步简化,但可读性较差:

end=“n”
xy=[]
而(结束=“n”):
xy.append([int(输入(“输入x值”)),int(输入(“输入y值”)]))
结束=输入(“最后输入?[y/n]”)
打印(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)