使用给定位置在Python中创建矩阵

时间:2014-04-25 07:28:36

标签: python

我一直在尝试根据位置列表创建矩阵

我在这里有一个清单:

temp = [7, 0, 6, 0, 0, 4, 0, 0]

编辑:     此列表表示8x8矩阵。 列表中的非零数字表示项目在矩阵中存在的行。它在temp中的位置表示项目在矩阵中存在的列。因此,temp中的第一项表示第一列中有一个项目,即矩阵的第7行。

我希望有一个看起来像这样的矩阵:

[[0, 0, 0, 0, 0, 0, 0, 0]
 [7, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 6, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 4, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0]]

其中列表中的非零数字表示列中1的位置。

l = []
for x in range(1, (len(temp)+1)):
    l1 = []
    count = 1
    for y in temp:
        if count == x:
            l1.append(y)
        else:
            l1.append(0)
        count += 1
    l.append(l1)

我有这个,但它错了,输出错误列表中的1。我已经尝试了所有尝试修复它(不知何故,这个代码使用4x4矩阵,我不知道为什么)但没有任何效果。

非常感谢一些指导。

2 个答案:

答案 0 :(得分:2)

这样做似乎是一种更简单的方法

def prep(index, item, my_list):
    my_list[item - 1] = item
    return my_list[::-1]

from pprint import pprint
pprint(zip(*[prep(idx, item, [0] * len(temp)) for idx, item in enumerate(temp)]))

<强>输出

[(0, 0, 0, 0, 0, 0, 0, 0),
 (7, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 6, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 4, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0),
 (0, 0, 0, 0, 0, 0, 0, 0)]

答案 1 :(得分:0)

以下代码应该有效:

temp = [7, 0, 6, 0, 0, 4, 0, 0]
pos=0
matrix=[]
for e in temp:
    l=[0]*len(temp)
    l[pos]=e
    matrix.append(l)
    pos=pos+1
print l