在尝试执行总计语句时,将索引脱离范围错误
我正在尝试执行多个总计语句,但它一直说索引超出范围。 这是代码部分:
for m in range(len(mo)):
for o in range(len(mag)):
if mag[o] == 0 and mo[m] ==1 :
countfujita[m] = countfujita[m] + 1
我试图将总数放入列表中,如下所示: 计数藤田 = [0,0,0,0,0,0]
I am trying to do a multiple totaling statements but it keeps saying index out of range.
Here is the section of code:
for m in range(len(mo)):
for o in range(len(mag)):
if mag[o] == 0 and mo[m] ==1 :
countfujita[m] = countfujita[m] + 1
and I am trying to get the totals into list a list such as this:
countfujita = [0,0,0,0,0,0]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑这是因为当您不需要时,您正在
mag
mo 中的每个项目。让我知道以下问题是否解决了您的问题:(这假定
len(mag)= len(mo)
)I suspect this is because you are looping over
mag
for every item inmo
when this is not what you want. Let me know if the following fixes your issue:(this assumes that
len(mag) = len(mo)
)为了使您的代码成功运行,您需要确保countfujita至少与mo列表一样长。
以下是一种可靠的方法:
输出:
In order for your code to run successfully you need to ensure that countfujita is at least as long as the mo list.
The following would be a robust approach:
Output:
嵌套循环内部的多个列表易用。通常,我们希望尽可能利用Python内置模块。
例如(从lancelot du lac定义的示例开始),我们可以使用
itertools.product
生成mo
和mag
的所有组合。枚举
为我们提供了与mo
元素相对应的索引:为了进一步推动此索引在所有
mo
索引中,然后计数。这将导致计数器对象计数器({0:1})
对象,类似于dict
,它可能根据您对countfujita 以后:
Indexing multiple lists inside nested loops is error-prone. In general we want to leverage the python built-in modules as much as possible.
For example (starting from the example defined by Lancelot du Lac) we can use
itertools.product
to generate all combinations ofmo
andmag
.enumerate
gives us the index corresponding to the element ofmo
:To push this even further, we can combine this with
Counter
to first generate a list of allmo
indices and then count. This results in a counter objectCounter({0: 1})
object, similar to adict
, which might or might not be appropriate depending on what you do withcountfujita
later on: