如何对存储为字符串的数字列表求和

2024-05-23 04:40:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的节目。用户必须输入其商品的所有价格,完成后输入:总计。然后,这应该是他们输入的所有价格的总和,并返回他们的总数。每次我运行这个程序,它都会说:

Traceback (most recent call last):
  File "C:\Users\dimei_000\Desktop\Python Benchmark Part II.py", line 24, in     <module>
    main()
  File "C:\Users\dimei_000\Desktop\Python Benchmark Part II.py", line 6, in main
    regReport(regCalc(regInput()))
  File "C:\Users\dimei_000\Desktop\Python Benchmark Part II.py", line 15, in  regCalc
    totalPrice=sum(int(priceItems[0:]))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list' 

我不能强迫单子是数字,但我想不出解决办法。

这是我的程序:

#Python Register Thingy
priceItems=[0]
total='total'
def main():
    regReport(regCalc(regInput()))
def regInput():
    user=input("Please enter the prices of your items, once you are done type: total.\n")     
    if(user==total):
        pass
    else:
        priceItems.append(int(user))
        regInput()
def regCalc(items):
    totalPrice=sum(int(priceItems[0:]))   
def regReport(total):
    print("""
====================================
    Kettle Moraine Ka$h Register
       Thanks for Shopping!
====================================
    Your total:""")
    return totalPrice
main()

Tags: pymaindefusersfileintiitotal
2条回答

如果您喜欢不太实用的样式,可以使用生成器表达式

totalPrice = sum(int(x) for x in priceItems))

最好将项转换为int,作为输入验证的一部分,以便创建int的列表

正如回溯所说,错误就在这里:

totalPrice=sum(int(priceItems[0:]))

这一行实际上包含一些错误:

  1. priceItems[0:]是从priceItems开始到结束的片段-换句话说,[0:]什么也不做。这并不是一个错误,但它是毫无意义的,并表明你并不真正知道你要用它来实现什么。

  2. int(priceItems[0:])正在尝试将列表转换为整数,这显然行不通。

  3. 如果您能够以某种方式将列表转换为整数,sum(int(priceItems[0:]))将尝试获取该整数的和,这也没有意义;您对一组数字求和,而不是一个数字。

相反,请使用函数^{}

totalPrice = sum(map(int, priceItems))

这将获取列表中的每个项,将其转换为整数并对结果求和。

不过,请注意,整件事可以写成:

print('Your total is:', sum(map(int, iter(lambda: input('Please enter the prices of your items, once you are done type: total.'), 'total')))) 

相关问题 更多 >

    热门问题