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

标签 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 + 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/

相关文章:

r - 根据列表项的行拆分列表

python - 如何在 Windows 中防止 subprocess.popen 到 "get lost"?

python - 如何合并 2 个 pandas 系列?

python - igraph 错误识别子同构?

python - 用 Python 制作钻石 ASCII 艺术

linux - 在 linux 中,如何仅按文件名比较两个目录并获取不匹配的结果列表

java - 使用流优化列表遍历

Python Matplotlib 线图与轮廓/imshow 对齐

python - 如何使用azureml中上传到pandas的数据集进行分析?

python - 如何识别字典中的匹配值并仅使用这些键创建一个新字符串?