2016-08-20 45 views
1

我怎樣才能插入字符列表中的每個元素爲矩陣(MXN) 我有蟒蛇這個代碼現在如何將一個字符列表中的每個元素插入到矩陣蟒蛇

key = raw_input('Key: ') 
text = raw_input('Text: ') 
text_c = list(text) 
while ' ' in text_c: 
    text_c.remove(' ')  
columns = len(key)    
rows = int(math.ceil(float(len(text_c))/float(len(key)))) 
matrix = [] 
for i in range(rows): 
    matrix.append([]) 
    for j in range(columns): 
     matrix[i].append(None) 

,我想要將text_c中的每個元素插入到矩陣中。無論矩陣是否填滿。 我該怎麼做。由於 (對不起我的英文不好)

+3

能否請您提供一個樣本輸入和輸出段,使您的代碼完全可運行?例如'tabla'沒有在您提供的代碼中正確定義。 – albert

+0

對不起,tabla是矩陣。我已經糾正它 –

+0

那麼樣品輸入/輸出怎麼樣? – albert

回答

1

您可以通過一些列表內涵結合爲實現這一目標如下:

number_columns = 6 
sample_string = 'abcdefghijklmnopqrstuvwxyzabcdefgh' 

l = [list(sample_string[i:i+number_columns]) for i in range(0, len(sample_string), number_columns)] 
matrix = [s if len(s) == number_columns else s+[None]*(number_columns-len(s)) for s in l] 

給予了matrix

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

首先我們切片sample_string轉換爲切片後轉換爲列表的所需長度(列數)的子串。

在我提供sample_string樣本代碼不是由給定的含義number_colums整除表示子efgh的最後一個列表不具有number_columns所需長度。爲了得到這個固定的,我們需要檢查每個列表的長度是否符合要求。如果沒有,我們將追加所需數量的None元素。

爲了擺脫我們需要

sample_string = sample_string.replace(' ', '') 

擴展代碼的任何空間這將用空字符串替換任何空間。所以

number_columns = 6 
sample_string = 'this is a sample string' 

sample_string = sample_string.replace(' ', '') 

l = [list(sample_string[i:i+number_columns]) for i in range(0, len(sample_string), number_columns)] 
matrix = [s if len(s) == number_columns else s+[None]*(number_columns-len(s)) for s in l] 

會導致

[['t', 'h', 'i', 's', 'i', 's'], 
['a', 's', 'a', 'm', 'p', 'l'], 
['e', 's', 't', 'r', 'i', 'n'], 
['g', None, None, None, None, None]] 
+0

非常感謝您bro –

+0

如果這解決了您的問題,請接受我的答案以便將問題標記爲已解決。 – albert

+0

完成!謝謝,我是新的網站 –

相關問題