use*_*517 2 python loops range
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
Run Code Online (Sandbox Code Playgroud)
我收到错误: 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])
Run Code Online (Sandbox Code Playgroud)
所以你的代码实际上在做:
x = sum(None)
Run Code Online (Sandbox Code Playgroud)
代码的工作版本:
def garden(seedList):
flower = [2, 5, 12]
flowers = []
for each in range(len(seedList)):
flowers.append(seedList[each] * flower[each])
return sum(flowers)
Run Code Online (Sandbox Code Playgroud)
更好的解决方案使用zip
:
def garden(seedList):
flower = [2, 5, 12]
totalFlowers = sum ( x*y for x,y in zip(flower, seedList) )
return totalFlowers
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
119 次 |
最近记录: |