2014-05-08 26 views
0

所以我有這樣的巨蟒-3碼輸入矩陣:決策矩陣行確定長度都一樣(python3)

matrix = [] 
lop=True 
while lop: 
    line = input() 
    if not line: 
     lop=False 
    if matrix != []: 
     if len(line.split()) != len(matrix[-1]): 
      print("Not same length") 
      menu() 
    values = line.split() 
    row = [int(value) for value in values] 
    matrix.append(row) 

但是,如果我進入

1 2 3 
4 5 6 7 
8 9 0 1 2 

我的代碼會讓它通過,但你可以注意到,第2行和第3行與第1行的長度不同;如何防止呢?該行必須與第1行的長度相同,否則它必須返回錯誤消息,如'行長度不相同。我不太確定如何做到這一點。也許:

for row in matrix: 
    if len(row) == matrix[1] 
     pass 
    else: 
     print('not same length') 

但它不起作用。

感謝

+0

檢查更新的代碼 –

+0

你縮進了關閉。我會編輯你的問題,然後嘗試該代碼:) –

+0

好吧,即時消息等待:)謝謝 –

回答

0

如果你想匹配的第一行長度,試試這個方法,

使用len(matrix[0])

for row in matrix: 
    if len(row) == len(matrix[0]): 
     pass 
    else: 
     print('not same lenght') 
+0

爲什麼使用'max(matrix)'?它沒有找到最長的一排,無論如何你也不需要最長的一排。 'max'需要在矩陣上進行額外的迭代,這將會轉換O(n^2)而不是O(n)。 – user2357112

+0

謝謝@ user2357112指向我。你是對的。我更新了我的答案。 – dhana

0

使用內置len()功能和break聲明。

matrix = [] 
lop =True 
while lop: 
    line = input('Enter your line: ') 
    if not line: 
     lop=False 
    if matrix != []: 
     if len(line.split()) != len(matrix[-1]): 
      print("Not same length") 
      break 
    values = line.split() 
    row = [int(value) for value in values] 
    matrix.append(row) 

這種形式運行:

bash-3.2$ python3 matrix.py 
Enter your line: 1 2 3 
Enter your line: 4 5 6 
Enter your line: 7 8 9 0 
Not same length 
bash-3.2$ 
+0

我試過了並且它不工作,它返回'if len(line.split())!= len(matrice [-1] .split()): AttributeError:'list'對象沒有屬性'split' –

+0

@Program_coder檢查更新代碼 –

+0

謝謝,這工作! –