如何找到嵌套循环中数字列表的总和?
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...
我需要找到如何计算每个循环的不定数的总和,我现在遇到的问题是循环没有重置每个人的每个值,而且我得到总和。
答案 0 :(得分: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就可以了。
答案 1 :(得分: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
答案 2 :(得分: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()
希望这能回答你的问题