[英]Wrong use of enumerate
I have a problem with my code: I have this array of tot我的代码有问题:我有这个数组
[112 100 22 90 12 48 115 85 13 40 99 93 100 27 21 14 23 100]
I defined a random solution function:我定义了一个随机解函数:
def randomSolution():
somma = 0;
for i in enumerate(tot):
if somma<=3600:
countS[i] = 1
somma = somma + tot[i]
else:
break
return countS
rand_sol = randomSolution()
print(rand_sol)
but Jupiter lab underlines me但木星实验室强调了我
Index Error: too many indices for array.
索引错误:数组索引过多。
Can someone help me?有人能帮我吗?
I'm trying to be very forgiving of the way this questions was posed.我试图非常宽容地提出这个问题的方式。 I take it you are just trying to understand how to populate an array called countS
我认为您只是想了解如何填充一个名为countS的数组
First things first, your array has no delimiters, which is a non-starter.首先,您的数组没有分隔符,这是一个非首发。 I've added commas to help us get over this hurdled.
我添加了逗号来帮助我们克服这个障碍。
You never provided countS , so I just created an empty list for us to fill.您从未提供countS ,所以我只是创建了一个空列表供我们填写。
Because countS is originally an empty list, you can't index it iteratively.因为countS 本来就是一个空列表,所以不能迭代索引。 I replaced
countS[i] = 1
with countS.append(1)
to append the new value iteratively to the list.我用
countS.append(1)
替换countS[i] = 1
以迭代地将新值附加到列表中。
You may need a refresher on how to use enumerate
because you are currently only unpacking the a single value.您可能需要重新了解如何使用
enumerate
,因为您当前仅解压缩单个值。 enumerate()
returns the index position in list and the value at the index - so you need to unpack both with something like for i, value in enumerate(tot):
enumerate()
返回列表中的索引位置和索引处的值 - 所以你需要用类似for i, value in enumerate(tot):
Here is the code that I got working - I hope this helps.这是我开始工作的代码 - 我希望这会有所帮助。 In the future, please provide everything necessary to run your code so that we can help you more effectively.
将来,请提供运行您的代码所需的一切,以便我们更有效地帮助您。
tot = [112, 100, 22, 90, 12, 48, 115, 85, 13, 40, 99, 93, 100, 27, 21, 14, 23, 100]
countS = []
def randomSolution():
somma = 0;
for i, value in enumerate(tot):
if somma<=3600:
countS.append(1)
somma = somma + tot[i]
else:
break
return countS
rand_sol = randomSolution()
print(rand_sol)
output输出
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.