使用用户输入填充2D列表,其中列的值迭代地增加1

时间:2012-01-29 15:44:54

标签: python

我要求用户输入ROW的值以填充2D列表。列的值将是iterativley增加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 个答案:

答案 0 :(得分: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]]

或者,如果您不想修改list2D

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

或者,使用numpy:

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.]]