2017-09-01 277 views

回答

0

沒有進攻,但噢,我的上帝,這是如此unpythonistic,我的眼睛流血。但顯然你必須從某處開始;) 我想你以前完成過C開發。在Python中,您不需要預先分配內存或數組。您也可以直接迭代任何迭代,不需要使用遞增的整數索引。

只要做到:

import random 
lista = [random.randrange(1, 7, 1) for q in range(5)] 
print(lista) 
total = sum(lista) 

這將創建listarandom.randrange()返回五個整數的列表。

您的問題是:當您做lista=[[] for q in range(5)]時,會得到5個空列表([[], [], [], [], []])的列表。然後當你lista[count].append(c)你最終列出一個包含整數的列表([[5], [1], [3], [4], [3]])。 sum然後將嘗試總結內部列表,而不是整數。那失敗了。

+0

這是一個更好的方法添加int值.. –

1

嗨您嘗試添加int值那麼列出,類型不匹配錯誤, 你必須嘗試與列表值

count = 0 
total = 0 
lista=[[]for q in range(5)] 
while count<len(lista): 
    import random 
    c=random.randrange(1,7,1) 
    lista[count].append(c) 
    total += lista[count][0] 
    count += 1 
print(lista) 
print total 
相關問題