代码错误不允许我进步

时间:2017-11-14 22:56:10

标签: python string floating-point type-conversion

运行此代码时出现错误

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

TypeError:float()参数必须是字符串或数字,而不是' list'

我不知道如何解决错误

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

2 个答案:

答案 0 :(得分: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])]

答案 1 :(得分:0)

>>> prices = {}
>>> prices['a'] = [1], [2]
>>> prices
{'a': ([1], [2])}

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

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

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