gpt4 book ai didi

Python 二维数组无法工作。帮忙~

转载 作者:太空宇宙 更新时间:2023-11-04 10:51:46 27 4
gpt4 key购买 nike

_R = [0] * 5
R = [_R] * 4

num_user = 0
num_item = 0

for i in range(8):
s = input().split()
for j in range(4):
s[j] = int(s[j])

R[s[0]][s[1]] = s[2]
print(s[0], s[1], R[s[0]][s[1]])
num_user = max(num_user, s[0])
num_item = max(num_item, s[1])

print("=====")

for i in range(num_user + 1):
for j in range(num_item + 1):
print(i, j, R[i][j])

exit()

可能你已经明白我要问什么了。输出让我感到困惑:

#output
1 2 3
2 4 2
1 1 5
3 2 2
2 2 1
3 3 4
1 4 3
2 1 4
=====
0 0 0
0 1 4
0 2 1
0 3 4
0 4 3
1 0 0
1 1 4
1 2 1
1 3 4
1 4 3
2 0 0
2 1 4
2 2 1
2 3 4
2 4 3
3 0 0
3 1 4
3 2 1
3 3 4
3 4 3

我这是怎么了?上次我用 Python 编码是 2.7,那是很久以前的事了。我忘记了什么重要的语法吗?

最佳答案

您正在以错误的方式创建列表列表:

>>> _R = [0] * 5
>>> R = [_R] * 4
>>> [id(x) for x in R] #here all objects are acually identical
[36635392, 36635392, 36635392, 36635392]

>>> R[0][1]=1 #changing one element changes all other elements as well
>>> R
[[0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0]]

最好以这种方式创建您的列表:

>>> R=[[0]*5 for _ in range(4) ]
>>> [id(x) for x in R]
[37254008, 36635712, 38713784, 38714664]
>>>

关于Python 二维数组无法工作。帮忙~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13376592/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com