Python: 每次循环计算总和

0 投票
3 回答
6621 浏览
提问于 2025-04-17 20:04

我该如何计算一个在嵌套循环中的数字列表的总和呢?

    s=0
    people=eval(input())
    for i in range(people):
        firstn=input()
        lastn=input()
        numbers=(eval(input()))

        print(firstn, lastn, numbers)
        for b in range(numbers):

        numbers=eval(input())
        s+=numbers

        print(b)

输入数据如下:

    5 #nubmer of people I need to calculate
    Jane #firstname
    Doe #lastname
    4 #number of floats for each person, pretty sure this is for the second loop
    38.4 #these are the floats that i need to calculate for each person to find their sum
    29.3
    33.3
    109.74
    William #loop should reset here as this is the next person's first name
    Jones
    2
    88.8
    99.9
    firstname
    lastname
    number of floats
    float1
    float2...

我需要找出如何计算每个循环中不确定数量的数字总和。现在我遇到的问题是,循环没有为每个人重置每个值,所以我得到了一个总和。

3 个回答

0

你的问题表达得不太清楚,不过如果我理解得没错,这个方法可能有效。

people = int(input('Enter number of people: ')) # eval is generally not a good idea
for i in range(people):
    firstn = input()
    lastn = input()

    numbers= int(input('Enter number: '))

    print(firstn, lastn, numbers)

    print(sum(numbers)) # prints sum of 0,1,2...numbers-1

这里假设你使用的是Python 3。如果你用的是Python 2.7,就把input()换成raw_input()

希望这能解答你的疑问。

1

这是我能想到的最简单的解决方案:

nop=int(input())
for _ in range(nop):
    fname,lname=input(),input()
    n=int(input())
    summ=sum(float(input()) for _ in range(n))
    print("For {0} {1} the sum is {2}".format(fname,lname,summ))

输出结果:

$ python3 foo.py < abc
For Jane Doe the sum is 210.74
For William Jones the sum is 188.7

其中 abc 包含:

2
Jane
Doe
4
38.4
29.3
33.3
109.74
William
Jones
2
88.8
99.9
1
s = []
people = int(raw_input())
for i in range(people):
    firstn = raw_input()
    lastn = raw_input()
    numbers = int(raw_input())

    print(firstn, lastn, numbers)
    temp = 0
    for b in range(numbers):
        numbers = float(raw_input())
        temp += numbers
    s.append(temp)
print(s)

我觉得如果你想记录内层循环的所有结果,而不是直接打印出来,你需要用一个列表。我测试了你给的输入,在Python2.7中是可以正常工作的。

撰写回答