类型错误:float() 参数必须是字符串或数字,而不是“列表”python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37629828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: float() argument must be a string or a number, not 'list' python
提问by Blazed
I have a problem with Python. This is my code:
我对 Python 有问题。这是我的代码:
def calcola():
a = input()
b = float(a[0].split("*"))
c = float(a[0].split("/"))
d = float(a[0].split("-"))
e = float(a[0].split("+"))
j = float(a[1].split("*"))
k = float(a[1].split("/"))
l = float(a[1].split("-"))
m = float(a[1].split("+"))
b = b[0]
c = b[1]
d = c[0]
e = c[1]
f = d[0]
g = d[1]
h = e[0]
i = e[1]
somma1 = b+c
somma2 = d+e
somma3 = f+g
somma4 = h+i
print(somma1)
print(somma2)
print(somma3)
print(somma4)
calcola()
I've recieved some errors:
我收到了一些错误:
Traceback (most recent call last): File "file.py", line 29, in calcola() File "file.py", line 3, in calcola b = float(a[0].split("*")) TypeError: float() argument must be a string or a number, not 'list'
回溯(最近一次调用):文件“file.py”,第 29 行,在 calcola() 文件“file.py”,第 3 行,在 calcola b = float(a[0].split("*"))类型错误:float() 参数必须是字符串或数字,而不是“列表”
How can I transform the number in the list?
如何转换列表中的数字?
回答by Moses Koledoye
You can't call float
on a list directly. You can use map
to call float
on each item in the list. Like so:
您不能float
直接调用列表。您可以使用map
调用float
列表中的每个项目。像这样:
b = map(float, a[0].split("*"))
In python 3.x
在 python 3.x 中
b = list(map(float, a[0].split("*")))
Or for more readability, use a list comprehension. Works for both python2 and python3:
或者为了提高可读性,请使用列表理解。适用于 python2 和 python3:
b = [float(s) for s in a[0].split("*")]
But be sure the items after splitting are floatable
但要确保拆分后的项目是可浮动的