Python:计算每个循环的和

2024-05-23 15:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如何找到嵌套循环中数字列表的和?

    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...

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


Tags: ofthetoinforinputevalrange
3条回答

你的问题措词很差,但如果我理解正确,这可能行得通。

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()

希望这能回答你的问题

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

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
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可以。

相关问题 更多 >