在循环中乘以从字符串转换为浮点数的数字列表时出现问题 (Python)

Trouble in multiplying list of numbers converted from string to float in a loop (Python)

我在这里尝试将存储在列表中但为字符串类型的数字相乘,显示此错误

TypeError: can't multiply sequence by non-int of type 'float'

我的列表数据样本

[5, 'BTCUSD', 'Sell', '9125.5', 6055, '0.66352527', 'Limit', 'Filled']

def calc():
num=0.0
den=0.0
for ids in listBox.selection():
    num=num+(float(listBox.item(ids)['values'][3]*float(listBox.item(ids)['values'][4]))) #Problem occurng here
    den=den+float((listBox.item(ids)['values'][4]))
    print(listBox.item(ids)['values'])
    print(num/den)
return 0

我可能需要更多关于 listBox,
的信息 但是当我粗略地看到给定的代码时,我认为导致错误的行应该像下面这样编辑:

# Original Code:
#   num=num+(float(listBox.item(ids)['values'][3]*float(listBox.item(ids)['values'][4])))
    num=num+(float(listBox.item(ids)['values'][3])*float(listBox.item(ids)['values'][4]))


TypeError: can't multiply sequence by non-int of type 'float'

当您尝试将序列(列表、字符串等)与浮点值相乘时,这实际上会发生:

a = 'hello'
print(a * 3.0)  # error

允许将一个序列乘以整数值,其作用相当于将序列重复n次:

a = 'hello'
print(a * 3)   # 'hellohellohello'

在您的代码中,您没有正确完成第一个 float() 函数。第二个 float() 函数做得很好,所以您只是想将一个字符串(尚未转换)与一个浮点值(转换良好)相乘。请仔细检查代码中的括号。谢谢。