简体   繁体   English

总结 Python 中直到列表末尾的行的所有列

[英]Sum Up All the Columns for Row Until End of List In Python

list=[[a],[b]]

it should return它应该返回

1.values sum of list[a] 1.values list[a]的总和

2.perform some operation 2.执行一些操作

3.and then go back to (1) and do sum of list[b] 3.然后 go 回到(1)并做列表的总和[b]

I tried below code:我尝试了以下代码:

K=[[a],[b]]
for ind,ele in enumerate(k):
    d=ele
    print(d)
    for j in range(len(d)):
        tot=tot+d[j]
        count=count+1
        print(tot)
    Avg=tot/count

Problem with this is it is performing only once i,e sum(k[a]) Your inputs are much appreciated问题是它只执行一次,即 sum(k[a]) 您的输入非常感谢

Here's a version of your code with just enough added to the top of it to allow it to run, along with a few extra print statements added to show the values that Avg takes on during execution (and one typo fixed...you were using both 'k' and 'K' for the name of the input list):这是您的代码的一个版本,在其顶部添加了足够的内容以使其运行,并添加了一些额外的打印语句以显示Avg在执行期间采用的值(并且修复了一个错字...您正在使用'k' 和 'K' 都是输入列表的名称):

a = 23
b = 1234
count = 0
tot = 0

k=[[a],[b]]
for ind,ele in enumerate(k):
        # count = 0
        # tot = 0
        d=ele
        print(d)
        for j in range(len(d)):
            tot=tot+d[j]
            count=count+1
            print(tot)
        Avg=tot/count
        print("The average at this point is:", Avg)

print("The average of all values is:", Avg)

Result:结果:

[23]
23
The average at this point is: 23.0
[1234]
1257
The average at this point is: 628.5
The average of all values is: 628.5

Result with initialization lines uncommented:未注释初始化行的结果:

[23]
23
The average at this point is: 23.0
[1234]
1234
The average at this point is: 1234.0
The average of all values is: 1234.0

This code works fine.这段代码工作正常。 It shows that your inner loop is executed twice, once per element in 'k/K'.它表明您的内部循环执行了两次,“k/K”中的每个元素执行一次。 Per your description, it seems like you want to isolate the sum of each sub-list so that the result of summing earlier lists does not affect Avg for the current list you are processing.根据您的描述,您似乎想要隔离每个子列表的总和,以便对早期列表求和的结果不会影响您正在处理的当前列表的Avg If that's the case, then you should initialize tot and count at the top of each iteration of your outer loop.如果是这种情况,那么您应该在外部循环的每次迭代的顶部初始化totcount You can do that by uncommenting the two lines I provide above that set those values to 0 inside the outer loop.您可以通过取消注释我在上面提供的将这些值设置为外循环内的0的两行来做到这一点。 If you do this, then you don't need to initialize these values at the top of the code.如果这样做,则无需在代码顶部初始化这些值。

So this shows your code working just fine.所以这表明你的代码工作得很好。 Given what I've said, what is the problem you're having?鉴于我所说的,你遇到了什么问题?

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

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