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

これは私が考えることができる最も簡単な解決策です:

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 に答える
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でOKです。

于 2013-03-23T17:29:29.520 に答える
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を使用していることを前提としています。Python2.7の場合は、を次のように置き換えますinput()raw_input()

これがあなたの質問に答えることを願っています

于 2013-03-23T17:26:31.663 に答える