繁体   English   中英

将文本列表转换为数字?

[英]Convert a text list to numbers?

我正在尝试使用float()将以下列表转换为数字。 但它总是说ValueError: could not convert string to float

我了解当文本中存在不能被视为数字的内容时会发生此错误。 但我的清单似乎没问题。

a = ['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3']

b = [float(x) for x in a]
a = ['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3']

b = [float(x) for x in a]

完美运行。

['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3']

b = [float(x) for x in a]

没那么多。

您的错误消息显示您的条目之一是单引号或列表中的空元素。 例如,

a = ['the', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3']

b = [float(x) for x in a]

抛出错误: ValueError: could not convert string to float: the

您发布的列表完全符合您的方法。

  • 要么你有a已定义为字符串,并没有指出了名单。

  • 该列表包含一个数字。

只是为了验证尝试

map(int,a) #if no errors you have all numbers

然后试试

set(map(type,a)) #if outputs {str} you should be good. 

无论哪种方式,您的错误都无法重现,并在您的问题中发布更多详细信息。

问题正是回溯日志所说的:无法将字符串转换为浮点数

  1. 如果您有一个只有数字的字符串,python 足够聪明,可以执行您正在尝试的操作并将字符串转换为浮点数。
  2. 如果您有一个包含非数字字符的字符串,则转换将失败并给出您遇到的错误。

您可以去除空格,然后检查字符串中的数字。

 f = open('mytext.txt','r') 
 a = f.read().split()
 a = [each.strip() for each in a]
 a = [each for each in a if each.isdigit() ]
 b = [float(each) for each in a]  # or b = map(float, a)
 print b
 # just to make it clear written as separate steps, you can combine the steps

您可以使用转换列表

如果您的列表中有任何字符串,那么您会收到错误消息ValueError: could not convert string to float like that

>>> a = ['4', '4', '1', '1', '1', '1', '2', '4', '8', '16', '3', '9', '27', '81', '4', '16', '64', '256', '4', '3']
>>> b = list(map(float, a))
>>> b

输出

[4.0, 4.0, 1.0, 1.0, 1.0, 1.0, 2.0, 4.0, 8.0, 16.0, 3.0, 9.0, 27.0, 81.0, 4.0, 16.0, 64.0, 256.0, 4.0, 3.0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM