2013-10-24 18 views
0

我正試圖找到一種更簡潔的方式來返回任意數量的NxN矩陣。 現在,我使用以下方式這個功能我正在尋找一種整潔的方式來返回python中的多個矩陣

from numpy import matrix, zeros 

def empty_matrix(dim, num): 
"""Returns an empty square matrix of type complex and size a.""" 
    if num == 1: 
     return matrix(zeros(shape =(dim, dim), dtype=complex)) 
    else: 
     return [ matrix(zeros(shape =(dim, dim), dtype=complex)) for _ in range(num)] 

A,B,C = empty_matrix(2, 3) # sets A, B, C as 3 2x2 matrices 

我試圖找出是否有以避免if/else語句的方式。有任何想法嗎?

+0

你可以找到在這個[問題]一些解決方案[1]。希望能幫助到你。 [1]:http://stackoverflow.com/questions/17869775/unpacking-variable-length-list-returned-from-function – fryday

回答

1

刪除該if num == 1,並使用1元元組,拆包:

A,B,C = empty_matrices(2, 3) # sets A, B, C as 3 2x2 matrices 
A, = empty_matrices(2, 1) # sets A as a 2x2 matrix 
相關問題