簡體   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