python-3.x - How to i add the return values of a loop
问题描述
I'm new to python a and I need to add the return values of a loop. the program is supposed to open a file containing dimensions in the format 1x31x6 sort them and do some math. I'm fairly certain I have everything right but I cannot figure out how to add the return values together. here is the code I have so far.
def parseAndSort(string):
"""this function reads the input file, parses the values, and sorts the ints from smallest to largest"""
int_list = string.split('x')
nums = [int(x) for x in int_list]
nums.sort()
length = nums[0]
width = nums[1]
height = nums[2]
surface_area = (2 * length * width) + (2 * length * height) + (2 * width * height) + (length * width)
tape = (2 * length) + (2 * width) + (length * width * height)
return surface_area
def main():
file = input('Please Input Measurement File :')
try:
output = open(file, "r")
except FileNotFoundError:
print("Error, please input a dimension file.")
else:
for ref in output:
parseAndSort(ref)
output.close()
if __name__ == "__main__":
""" This is executed when run from the command line """
main()
解决方案
我假设您的意思是您想要运行该函数的所有时间的返回值的总和。您可以保持一个运行总和,并不断将每个返回值添加到其中。
def main():
sum = 0
file = input('Please Input Measurement File :')
try:
output = open(file, "r")
except FileNotFoundError:
print("Error, please input a dimension file.")
else:
for ref in output:
sum += parseAndSort(ref)
output.close()
print (sum)
推荐阅读
- java - 无法在 HackerRank 中执行 Java IF-ELSE 程序
- javascript - 在 HTML 模式中包含过滤器列表
- javascript - 组合多个参数装饰器
- python - QWebengineview 哈希值无法处理,因为它是空的。请确认您的 redirectUri 未清除哈希
- jquery - 如何在for循环中切换单击按钮的类?
- ios - SwiftUI 键盘关闭问题
- kql - Kusto 中的列表理解等效项
- javascript - 如何在 web ar 中使用 nft 使内容(模型/视频)留在屏幕上?
- c# - 转发 multipart/x-mixed-replace 直播流 ASP.NET Core
- r - 将每个值与同一列中的其他值重复