簡體   English   中英

列表,For循環,范圍,索引

[英]Lists, For Loops, Ranges, Indexes

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. 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.

我需要解決的問題:

編寫一個函數,根據給定每種花的種子數量,計算出花的總量。 seedList參數將包含您擁有的種子數量。 每粒種子都會產生一定數量的花。 一顆矮牽牛種子將產生2朵花,一顆雛菊種子將產生5朵花。 一朵玫瑰種子將產生12朵花。每種花的種子。 seedList參數將包含您擁有的種子數量。 您應該返回一個整數,其中包含您在花園中將要開花的總數。

問題是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM