我正在尝试使用以下代码在 python 中填充空矩阵(列表列表)的对角线:
source=['a','b','c']
rows=[]
for x in source:
rows.append('')
matrix=[]
for x in source:
matrix.append(rows)
print "before populating", matrix
for x in range (0, len(source)):
matrix[x][x]=source[x]
print "after populating", matrix
我意识到这不是实现此目的的最有效方法,但这实际上似乎是我遇到的最少的问题。
我得到的输出是这样的:
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
但我希望的输出是这样的:
[['a', '', ''], ['', 'b', ''], ['', '', 'c']]
知道哪里出了问题吗?非常感谢!
请您参考如下方法:
for x in source:
matrix.append(rows)
您使用对行的引用填充矩阵。您可以使用 行 的切片来制作副本
>> rows = ['a','b','c']
>>> matrix = [rows[:] for _ in range(len(rows))]
>>> matrix
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> matrix[1][1]=' '
>>> matrix
[['a', 'b', 'c'], ['a', ' ', 'c'], ['a', 'b', 'c']]
