繁体   English   中英

Grok 学习:如何编写 Python 程序来读入整数成本列表,并打印出所有成本的总和

[英]Grok Learning: How to write a Python program to read in a list of integer costs, and print out the total sum of all of the costs

Python 新手,正在使用 Grok Learning 进行 Python 编程介绍。 我有这个问题,我需要输入,转换为列表,转换为整数,然后收集整数的总和。 这是我到目前为止所拥有的:

expenses = input("Enter the expenses: ")
expenses.split()
for expense in expenses:
  print(int(expenses))
total = sum(expenses)
print("Total: $" + total)

有人告诉我必须遍历数组然后转换为整数。 但我不知道这是什么意思,有人可以告诉我吗?

由于您已经编写了for循环,我假设您知道它的含义,因此您只需要创建另一个列表来存储 int 值:

intValues = []
for expense in expenses:
    intValues.append(int(expense))

然后print(sum(intValues))工作原理相同。 您可以使用 Python 的列表理解语法在一行中完成相同的操作:

intValues = [int(expense) for expense in expenses]

要修复您的错误,请尝试以下操作:

expenses = input("Enter the expenses (separated by spaces): ")
total = 0
for expense in expenses.split():
  total += int(expense)
  print(expense)
print( "Total: $" + str(total) )

示例会话:

Enter the expenses (separated by spaces): 12 34 56
12
34
56
Total: $102

首先,您需要将 total=sum(expenses) 缩进 for 循环并需要将拆分结果保存在一个变量中,因此修改后的程序是:

expenses = input("Enter the expenses: ")
for expense in expenses.split:
  print(int(expense))
  total = sum(expense)
print("Total: $" + total)

试试这个:

expenses = input('Enter the expenses: ')
expenses = expenses.split()

total = 0
for expense in expenses:
  total += int(expense)

print('Total: $' + str(total))

当我完成这个挑战时,这是我的代码:

money = input("Enter the expenses: ")
money = money.split()
total = sum([int(i) for i in money ])
print("Total:", "$" + str(total))

第一行只是钱的输入。 第二行将每个数字拆分为一个列表。 第 3 行将输入的总和计算为整数,然后第 4 行将其改回字符串并打印出来。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM