在没有numpy的Python中创建矩阵

2024-06-08 05:25:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建和初始化一个矩阵。我的问题是我创建的矩阵的每一行都是相同的,而不是在数据集中移动。 我试图通过检查值是否已经在矩阵中来纠正它,但这并不能解决我的问题。

def createMatrix(rowCount, colCount, dataList):   
    mat = []
    for i in range (rowCount):
        rowList = []
        for j in range (colCount):
            if dataList[j] not in mat:
                rowList.append(dataList[j])
        mat.append(rowList)

    return mat 

def main():  
    alpha = ['a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    mat = createMatrix(5,5,alpha)
    print (mat)

输出应如下: ['a','b','c','d','e'],['f','h','i','j','k'],['l','m','n','o','p'],['q','r','s','t','u',['v','w','x','y','z']

我的问题是,我只是不断得到所有5个列表返回的第一个a、b、c、d、e列表


Tags: 数据inalpha列表fordefrange矩阵
2条回答

您可以使用列表理解:

>>> li= ['a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
>>> [li[i:i+5] for i in range(0,len(li),5)]
[['a', 'b', 'c', 'd', 'e'], ['f', 'h', 'i', 'j', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z']]

或者,如果不介意使用元组,请使用zip:

>>> zip(*[iter(li)]*5)
[('a', 'b', 'c', 'd', 'e'), ('f', 'h', 'i', 'j', 'k'), ('l', 'm', 'n', 'o', 'p'), ('q', 'r', 's', 't', 'u'), ('v', 'w', 'x', 'y', 'z')]

或者对元组应用list

>>> map(list, zip(*[iter(li)]*5))
[['a', 'b', 'c', 'd', 'e'], ['f', 'h', 'i', 'j', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z']]

您需要跟踪循环中的当前索引。

实际上,您需要将0、1、2、3、4、….24(这些是初始数组alpha的索引)等列表转换为:

R1C1, R1C2, R1C3, R1C4, R1C5 R2C1, R2C2... etc

我添加了这样做的逻辑:

def createMatrix(rowCount, colCount, dataList):
    mat = []
    for i in range(rowCount):
        rowList = []
        for j in range(colCount):
            # you need to increment through dataList here, like this:
            rowList.append(dataList[rowCount * i + j])
        mat.append(rowList)

    return mat

def main():
    alpha = ['a','b','c','d','e','f','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    mat = createMatrix(5,5,alpha)
    print (mat)

main()

然后打印出来:

[['a', 'b', 'c', 'd', 'e'], ['f', 'h', 'i', 'j', 'k'], ['l', 'm', 'n', 'o', 'p'], ['q', 'r', 's', 't', 'u'], ['v', 'w', 'x', 'y', 'z']]

您总是收到a,b,c,d,e的原因是,当您编写此文件时:

        rowList.append(dataList[j])

它实际上是在为每一行迭代0-4。所以基本上:

i = 0
rowList.append(dataList[0])
rowList.append(dataList[1])
rowList.append(dataList[2])
rowList.append(dataList[3])
rowList.append(dataList[4])
i = 1
rowList.append(dataList[0]) # should be 5
rowList.append(dataList[1]) # should be 6
rowList.append(dataList[2]) # should be 7
rowList.append(dataList[3]) # should be 8
rowList.append(dataList[4]) # should be 9

等等

相关问题 更多 >

    热门问题