1
_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,那是很久以前的事了。我忘记了什么重要的语法吗?

4

2 回答 2

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

那是一个NOGO。R 将包含 _R 4 次,相同的数组 4 次...

改用这个:

R = [[0 for col in range(5)] for row in range(4)]
于 2012-11-14T10:03:01.603 回答
2

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

>>> _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]
>>> 
于 2012-11-14T10:05:08.837 回答