【问题标题】:Error in code wont allow me to progress代码错误不会让我进步
【发布时间】:2017-11-14 22:56:09
【问题描述】:

运行这段代码时出现错误

cost = float(prices[strs[0]][0])

TypeError: float() 参数必须是字符串或数字,而不是“列表”

我不知道如何修复错误

prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit", 
"cost", "total")

print(headings)
finalCost = 0

for strs in groceries
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = float(prices[strs[0]][0])

【问题讨论】:

  • 就在最后一行之前,添加 print(prices[strs[0]][0]) 并查看您传递给 float 的类型是什么。错误表明它是列表。因此,您的索引逻辑可能不正确。
  • 使用cost = float(prices[strs[0]][0][0])。或者你可能想要prices[strs[0]] = [strs[1], strs[2]],我认为你首先想要的。
  • 我的解决方案将两个价格都转换为浮动,而不仅仅是第一个。
  • cost = [float(v) for v in prices[strs[0]][0]]
  • 请将帮助您的答案标记为正确。欢迎来到堆栈溢出!

标签: python string floating-point type-conversion


【解决方案1】:

prices[strs[0]][0] 是一个包含两个价格的list。因此,您需要分别转换这两个值或使用cost = [float(v) for v in prices[strs[0]][0]]

prices = {}
groceries = []

file = open("grocery_store_price_list.txt", "r")
for strx in file:
    strs = list(filter(None, strx.strip().split(" ")))
    prices[strs[0]] = [strs[1]], [strs[2]]  # List of two prices, why you get the error.
file.close()

file = open("my_personal_gro_list.txt", "r")
for strx in file :
    strs = list(filter(None, strx.strip().split(" ")))
    groceries.append([strs[1], strs[0]])

headings = "{:15s} {:3s} {:10s} {:5s} {:6s}".format("item", "qty", "unit", 
"cost", "total")

print(headings)
finalCost = 0

for strs in groceries
    item = strs[0]
    qty = int(strs[1])
    unit = prices[strs[0]][1]
    cost = [float(v) for v in prices[strs[0]][0]]
    # OR  cost = [float(prices[strs[0]][0][0]), float(prices[strs[0]][0][1])]

【讨论】:

    【解决方案2】:
    >>> prices = {}
    >>> prices['a'] = [1], [2]
    >>> prices
    {'a': ([1], [2])}
    

    以上面为例,您的价格包含一个元组,每个是一个包含 1 个元素的列表

      prices[strs[0]] = [strs[1]], [strs[2]]
    

    您可以在其中一个值上应用 float() 或修改您的 prices 让每个键都有一个值

    【讨论】:

    • 相信它是list
    • 价格[strs[0]] = [strs[1]], [strs[2]]
    • @alexisdevarennes 谢谢,它是一个包含 2 个单项列表的元组。 [2] 本身就是一个列表,这应该是 Op 得到错误的原因
    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2012-09-16
    • 2020-05-05
    相关资源
    最近更新 更多