0

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

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

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

4

3 回答 3

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 没问题。

于 2013-03-23T17:29:29.520 回答
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
于 2013-03-23T17:59:59.867 回答
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()

希望这能回答你的问题

于 2013-03-23T17:26:31.663 回答