2013-05-30 67 views
2
def garden(seedList): 
    flower = [2, 5, 12] 
    flowers = [] 
    for each in range(len(seedList)): 
    totalFlowers = flowers.append(seedList[each] * flower[each]) 
    x = sum(totalFlowers) 
    return totalFlowers 

我得到錯誤:The error was:iteration over non-sequence Inappropriate argument type. An attempt was made to call a function with a parameter of an invalid type. This means that you did something such as trying to pass a string to a method that is expecting an integer.列表,For循環,範圍,指標

,我需要解決的問題:

Write a function that calculates the total amount of flowers given the number of seeds for each type of flower. The seedList parameter will contain the amount of seeds you have. Each seed will produce a certain number of flowers. One petunia seed will produce 2 flowers.One daisy seed will produce 5 flowers. One rose seed will produce 12 flowers.seeds for each type of flower. The seedList parameter will contain the amount of seeds you have. You should return an integer with the total number of flowers you will have in your garden.

+1

通過循環索引在Python中是一個非常糟糕的主意 - 閱讀困難,速度慢,靈活性差。當用於像這樣一次迭代兩個列表時,這也意味着行爲更加不穩定。循環值! (len(seedList)):' - >'種子,花中zip(seedList,flower):''和'flowers.append(seedList [each] * flower [each])' - >'flowers .append(seed * flower_)'。 –

回答

6

問題是list.append就地修改列表並返回None

totalFlowers = flowers.append(seedList[each] * flower[each]) 

所以你的代碼實際上是這樣做的:

x = sum(None) 

你的代碼的工作版本:

def garden(seedList): 
    flower = [2, 5, 12] 
    flowers = [] 
    for each in range(len(seedList)): 
     flowers.append(seedList[each] * flower[each]) 

    return sum(flowers) 

更好的解決方案解決方案使用zip

def garden(seedList): 
    flower = [2, 5, 12] 
    totalFlowers = sum (x*y for x,y in zip(flower, seedList)) 
    return totalFlowers