简体   繁体   English

在 python 中嵌套 for 循环以执行以下操作

[英]nested for loop in python to do the following

I am trying to write an equation for a nested for loop.我正在尝试为嵌套的 for 循环编写一个方程式。 i am getting an error and am trying to understand how to write it?我收到一个错误并试图了解如何编写它?

ysub =  GPA
0   0.4509999999999996
1   -0.04900000000000038
2   -0.5490000000000004
3   0.20099999999999962
4   -0.4490000000000003
5   0.19099999999999984
6   0.4509999999999996
7   -0.5490000000000004
8   0.25099999999999945
9   0.05099999999999971

Code:代码:

i = range (1,10,1)
m = range (1,10,1)
 RMSEtest = ((1/m)*(ysub[i]^2))

we have to calculate RMSEtest (sum of values from m = 1 to 10) for each of the ysub values.我们必须为每个 ysub 值计算 RMSEtest(从 m = 1 到 10 的值的总和)。

first of all that is not a for-loop.首先这不是一个for循环。 You really don't need to add a third parameter to the range because the default is 1 .您真的不需要向range添加第三个参数,因为默认值为1 Your question is unclear about what you need the for-loop to do and the code doesn't help.您的问题不清楚您需要 for 循环做什么,并且代码没有帮助。
For nested for-loops, you want something like:对于嵌套的 for 循环,您需要类似:

for x in I:
    for y in m:
        do_something(x, y)

There were a lot of mistakes有很多错误

  1. you cannot divide integer with a range object as told by @ForceBru.正如@ForceBru 所说,您不能将 integer 与 object 范围相除。

  2. You don't need 2 loops for your work您的工作不需要 2 个循环

  3. To raise the power of an integer or a float, '**' is used instead of '^'为了提高 integer 或浮点数的功率,使用“**”而不是“^”

     ysub = [0.4509999999999996, -0.04900000000000038,-0.5490000000000004,0.20099999999999962,-0.4490000000000003, 0.19099999999999984, 0.4509999999999996, -0.549000000000000, 0.25099999999999945, 0.05099999999999971]

Code:代码:

for m in range (1,10):
    RMSEtest = ((1/m)*(ysub[m]**2))

From your code, I think this is what you wanted.从您的代码中,我认为这就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM