用用户输入填充二维列表,列值逐个递增

0 投票
1 回答
963 浏览
提问于 2025-04-17 11:53

我让用户输入行的数量,以便填充一个二维列表。列的数量会逐渐增加,每次加1。

list2D = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
user input = [1,3,0,2]  ##indexes of rows as well as values

也就是说:

0th column the row = 1
1 column row = 3
2 column row = 0
3 column row = 2

所以新的列表将会是:

newList = [[0,0,**0**,0],[1,0,0,0],[0,0,0,2],[0,3,0,0]]

该怎么做呢?

1 个回答

4
list2D = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
user_input = [1,3,0,2]
for col,row in enumerate(user_input):
    list2D[row][col] = row

print(list2D)
# [[0, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 2], [0, 3, 0, 0]]
import copy    
list2D = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
user_input = [1,3,0,2]
newList = copy.deepcopy(list2D)
for col,row in enumerate(user_input):
    newList[row][col] = row
import numpy as np

list2D = np.zeros((4,4))
user_input = [1,3,0,2]
list2D[user_input,range(4)] = user_input
print(list2D)
# [[ 0.  0.  0.  0.]
#  [ 1.  0.  0.  0.]
#  [ 0.  0.  0.  2.]
#  [ 0.  3.  0.  0.]]

或者,如果你不想修改 list2D

或者,使用 numpy:

撰写回答