2017-04-03 64 views
-1

我想做一個進化模擬器,但程序不斷拋出這個錯誤「TypeError:'元組'對象不支持項目分配」。該程序假設創建兩個隨機生物,然後給他們一個隨機突變並打印生物的價值。隨着一些小動作,我已經得到它來拋出一個錯誤,只打印第一個生物,或打印兩個沒有突變的生物。任何幫助?Evolution模擬器:TypeError:'元組'對象不支持項目分配

import random 
from random import randint 

creatures = (random.randint(1, 10), random.randint(1, 10)) 


print(creatures) 

for i in creatures: 
    randomMutation = random.randint(1, 2) 
    creatures[i] = i + randomMutation 

for i in range(newEvolution): 
    print("New evolution", newEvolution) 

newEvolution應該是一個添加了突變的生物列表。

+0

元組是不可變的,使用列表代替 – fiacre

+0

newEvolution沒有在任何地方定義,我不明白你的代碼。 – fedeisas

回答

1

錯誤非常簡單。 Tuples do not support item assignment:它們是不可變的。改爲使用列表。

Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples).

正確的代碼:

import random 
from random import randint 

creatures = [random.randint(1, 10), random.randint(1, 10)] 

print(creatures) 

for index, value in enumerate(creatures): 
    randomMutation = random.randint(1, 2) 
    creatures[index] = value + randomMutation 
0

生物是元組,你試圖通過 生物[i] = I + randomMutation ,因爲它們是不可變的,這是不可能的元組的情況下,爲它們分配請按照fedeisas建議使用列表

相關問題