简体   繁体   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

I am getting error: 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. 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 problem that I need to solve: 我需要解决的问题:

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. seedList参数将包含您拥有的种子数量。 Each seed will produce a certain number of flowers. 每粒种子都会产生一定数量的花。 One petunia seed will produce 2 flowers.One daisy seed will produce 5 flowers. 一颗矮牵牛种子将产生2朵花,一颗雏菊种子将产生5朵花。 One rose seed will produce 12 flowers.seeds for each type of flower. 一朵玫瑰种子将产生12朵花。每种花的种子。 The seedList parameter will contain the amount of seeds you have. seedList参数将包含您拥有的种子数量。 You should return an integer with the total number of flowers you will have in your garden. 您应该返回一个整数,其中包含您在花园中将要开花的总数。

Problem is list.append modifies the list in place and returns None . 问题是list.append修改列表到位并返回None

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

So your code is actually doing : 因此,您的代码实际上正在执行:

x = sum(None)

A working version of your code: 您的代码的有效版本:

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

  return sum(flowers)

A better solution solution using zip : 使用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