【发布时间】: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