如何汇总存储为字符串

时间:2015-06-09 22:53:14

标签: python python-3.x

这是我的计划。用户必须输入其物品的所有价格,并在完成后输入:总计。然后,这应该将他们输入的所有价格加起来并将它们归还总额。每次我运行程序时,都会说:

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()

2 个答案:

答案 0 :(得分:4)

正如追溯所说,错误在于:

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

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

  1. priceItems[0:]是从priceItems开始到结尾的切片 - 换句话说,[0:]无效。这不是一个错误,但它 毫无意义,并暗示你并不真正知道你用它来实现的目标。

    < / LI>
  2. int(priceItems[0:])正在尝试将列表转换为整数,这显然不会起作用。

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

  4. 相反,请使用函数map

    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')))) 
    

答案 1 :(得分:1)

如果您喜欢功能较少的样式,可以使用生成器表达式

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

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

列表
相关问题