【问题标题】:Storing Results in n*m Matrix in Python在 Python 中将结果存储在 n*m 矩阵中
【发布时间】:2019-06-24 16:25:06
【问题描述】:

我想将结果存储到一个 4*9 的矩阵中。我已经发布了我的代码,并且我正在使用嵌套的 for 循环。

我在如何存储结果时遇到了困难。

for d in range(4):
    for l in range(9):
         a=Swaps(n,d)
         k=Permute1(a,v,n)
         d = {x[-1]: x[:-1] for x in k}
         y= Permute2(a,v1,n)
         d1 = {x[-1]: x[:-1] for x in y}
         n=Bidirectional_Search(d,d1) #where n is a string

任何帮助将不胜感激

【问题讨论】:

标签: python for-loop matrix multidimensional-array


【解决方案1】:

你只需要在循环之外创建一个空列表。

matrix = []
    for d in range(4):
        row = []
        for l in range(9):
             a=Swaps(n,d)
             k=Permute1(a,v,n)
             d = {x[-1]: x[:-1] for x in k}
             y= Permute2(a,v1,n)
             d1 = {x[-1]: x[:-1] for x in y}
             n=Bidirectional_Search(d,d1) #where n is a string
             row.append(n)
        matrix.append(row)

此操作后会有一个列表列表。

matrix == [
    [element00, element01, ..., element08],
    [element10, element11, ..., element18],
    [element20, element21, ..., element28],
    [element30, element31, ..., element38],
]

您可以使用以下语法访问元素:

matrix[0][1] # will return element01

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2013-02-08
    • 2012-05-18
    相关资源
    最近更新 更多