以特殊形式python打印矩阵

时间:2015-10-14 12:03:37

标签: python matrix

我需要编写一个函数,当给定输入矩阵时,将根据特殊顺序读取和打印矩阵。代码应该顺时针绕过边界打印矩阵。例如,如果矩阵是

[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]

它会输出列表

1,2,3,4,5,5,5,4,3,2,1,1

我知道它需要一个for循环,所以我创建了for循环,它将打印第一行,但我不知道如何去那里。我觉得我必须将矩阵中每个列表的最终数量定义为n-1,其中n是长度

4 个答案:

答案 0 :(得分:3)

这可以通过一个简单的单线程来完成:

>>> m = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
>>> print((lambda M:[m[p[1]][p[0]]for p in sorted([(x,y)for x in range(len(m[0]))for y in range(len(m))if x in(0,len(m[0])-1)or y in(0,len(m)-1)],key=lambda p:M.atan2(len(m)/2.0-p[1],len(m[0])/2.0-p[0])+(2*M.pi if M.atan2(len(m)/2.0-p[1],len(m[0])/2.0-p[0])<M.atan2(len(m)/2.0,len(m[0])/2.0)else 0))])(__import__("math")))

[1, 2, 3, 4, 5, 5, 5, 4, 3, 2, 1, 1]

答案 1 :(得分:1)

使用-1索引python列表将返回列表的最后一个元素,因此无需考虑n-1

reversed返回一个生成器,它以相反的顺序返回所提供的iterable的元素,而不创建参数的副本。

m=[[1, 2, 3, 4, 5],[1, 2, 3, 4, 5],[1, 2, 3, 4, 5]]

def get_edges(M):
    res = M[0]
    for l in M[1:-1]:
        res.append(l[-1])
    res += reversed(M[-1])
    for l in reversed(M[1:-1]):
        res.append(l[0])

    return res


print get_edges(m)

答案 2 :(得分:0)

检查:

data =[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]
for i in range(len(data[0])):
    print data[0][i]
for i in range(1,len(data)-1):
    print data[i][len(data[i])-1]
for i in range(len(data[len(data)-1])-1,0,-1):
    print data[len(data)-1][i]
for i in range((len(data)-1),0,-1):
    print data[i][0]

答案 3 :(得分:0)

这不是最有效的方式,但确实有效 并且有些pythonic。

#matrix is represented as list of list form for simplicity
matrix = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]  


def find_border(matrix):
    result=[]

    #printing up
    for i in matrix[0][:-1]:  #Slicing the first row to exclude the last element
        result.append(i)

    #right
    for row in matrix:
        result.append(row[-1]) #Getting last element of each row

    #down
    for i in list(reversed(matrix[-1]))[:-1]: #Iterating the last row in reversed order and leaving the 1st element of last row
        result.append(i)

    #left
    for row in reversed(matrix): #Iterating through rows in reversed , getting first element
        result.append(row[0])

    print(",".join([str(i) for i in result])) #Printing result in whatever manner required

find_border(matrix)