试图迭代python数组中的特定列

时间:2014-07-08 16:42:10

标签: python arrays

我正在尝试以数组格式创建字典列表。 最初我希望第一行和第一列有

{'score' : 0, 'pointer' : 'none'}

在每个单元格中,但是我的for循环似乎没有执行此操作 以下是我到目前为止的情况:

mymatrix = [[0 for x in range(len(seq1)+1)]for x in range(len(seq2)+1)]

mymatrix[0][0] = {'score' : 0, 'pointer' : 'none'}

for x in mymatrix[0][:]:
    x = {'score' : 0, 'pointer' : 'none'}
for y in mymatrix[:][0]:
    y = {'score' : 0, 'pointer' : 'none'}

for row in mymatrix:
    print row

其中seq1和seq2是字符串。

2 个答案:

答案 0 :(得分:1)

你已经在列表理解中写了两个for循环,你可以重复使用它们。

(我修改了您的列表理解,我使用了yx而不是2 x

seq1 = 'asdfasdfasdf'
seq2 = 'asdfasdfasdf'

mymatrix = [[0 for y in range(len(seq1)+1)]for x in range(len(seq2)+1)]
#              ^^^^^^^^^^^^^^^^^^^^^^^^^^ reuse this


d = {'score' : 0, 'pointer' : 'none'}

for y in range(len(seq1)+1):
    mymatrix[0][y] = d.copy()

# The first one is already covered, just leave it off using slice
for x in range(len(seq2)+1)[1:]:
    mymatrix[x][0] = d.copy()

for line in mymatrix:
    print(line)

出:

[{'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}, {'pointer': 'none', 'score': 0}]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[{'pointer': 'none', 'score': 0}, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

答案 1 :(得分:0)

据我所知,问题在于:

x = {'score' : 0, 'pointer' : 'none'}

这行代码不会改变实际的矩阵。你在这里所做的就是重新分配名称x的值,这个值本身并不是你想要改变的矩阵。您需要直接引用矩阵。试试这个:

for xind, x in enumerate(mymatrix[0][:]):
  mymatrix[0][xind] = {'score' : 0, 'pointer' : 'none'}