2014-03-01 201 views
0

基本上,我試圖創建一個程序,它將用1和6之間的隨機整數替換diceList的值,無論我的indexList在哪裏都有1。這是我到目前爲止有:替換列表中的值

import random 
def replaceValues(diceList, indexList): 
    newList = diceList 
    for i in indexList: 
     if indexList == 1: 
      newList[i] = random.randint(1,6) 
     return newList 

我執行replaceValues([1,2,3,4,5], [0,1,0,1,0])什麼,我應該得到的是[1,x,3,x,5]其中x應該是1和6之間的隨機數的問題是,它目前正在返回[1,2, 3,4,5]

+0

你的意思是'和6'之間2,對不對? – thefourtheye

+1

...發現有什麼問題? –

+0

不,我的意思是1和6,但我看到我所做的錯誤,現在它只是返回列表[1,2,3,4,5] – user3367018

回答

2

indexList a list?如果是這樣,list == 1是什麼意思?

if indexList == 1: 
    newList[i] = random.randint(1,6) 

您是否意思是i == 1

編輯:

我認爲你在尋找這樣的事情:

def replaceValues(diceList, indexList): 
    newList = diceList 
    if len(diceList) == len(indexList): 
     for pos in range(0, len(indexList)): 
      if indexList[pos] == 1: 
       newList[pos] = random.randint(0,6) 
     return newList 
+0

是indexList是一個零和一個列表。無論哪裏出現「1」,那麼它應該用「1」處的隨機數替換diceList – user3367018

+0

對不起,我對你現在想要的有了更好的理解。更新了我的帖子。 –

+0

謝謝賈斯汀!這工作! – user3367018