矩阵印刷印刷与循环相反

时间:2016-02-26 02:27:34

标签: python loops matrix

我练习用矩阵循环,但我真的坚持了一个小时。

A = [[1, 2, 3, 4, 5, 6],
     [7, 8, 9, 10, 11, 12],
     [13, 14, 15, 16, 17, 18],
     [19, 22, 21, 22, 23, 24]]

这是我的Matrix,基本上我想改变每一行的循环感觉。

我的功能是只打印值:

def clearPrint(Matrix):
i = 0
j = 0
result=[]
longLigne = len(Matrix)
longCol = len(Matrix[i])

for i in range(0, longLigne):
    print(" ")
    for j in range (0, longCol):
        result = Matrix[i][j] 
        print(result, end=" ")

当谈到切换反向循环时,我不知道如何......

以下是我试图获得的结果

A = [[1, 2, 3, 4, 5, 6],
     [12, 11, 10, 9, 8, 7],
     [13, 14, 15, 16, 17, 18],
     [24, 23, 22, 21, 20, 19]]

任何建议都会有所帮助

3 个答案:

答案 0 :(得分:2)

一衬垫:

A = [v[::-1] if i % 2 == 1 else v for i, v in enumerate(A)]

答案 1 :(得分:0)

a = [[1, 2, 3, 4, 5, 6],
     [7, 8, 9, 10, 11, 12],
     [13, 14, 15, 16, 17, 18],
     [19, 22, 21, 22, 23, 24]]

for x in a:
    if a.index(x) % 2 != 0:
        print (x[::-1])
    else:
        print (x)

输出;

[1, 2, 3, 4, 5, 6]
[12, 11, 10, 9, 8, 7]
[13, 14, 15, 16, 17, 18]
[24, 23, 22, 21, 22, 19]
>>> 

[::-1]将撤消列表。

答案 2 :(得分:0)

另一种可能的方法:

def clearPrint(Matrix):
    for i in range(0, len(Matrix)):
        if i % 2 != 0:
            print(list(reversed(Matrix[i])))
        else:
            print(Matrix[i])

A = [[1, 2, 3, 4, 5, 6],
 [7, 8, 9, 10, 11, 12],
 [13, 14, 15, 16, 17, 18],
 [19, 22, 21, 22, 23, 24]]

clearPrint(A)