[英]In Python how do you convert strings in a list of list to other types, such as ints, floats, booleans, etc?
當給出數據列表時,我被要求將列表中的字符串轉換為相應的類型,如果字符串包含整數,則為int;如果不包含整數,則為float。 但我遇到了這個問題,它將轉換值,但它不會更改列表中的原始值。
例如,如果給出:
d = [['abc', '123', '45.6', 'True', 'False']]
它應該在轉換后看起來像這樣:
[['abc', 123, 45.6, True, False]]
到目前為止,我已經嘗試編寫for循環並以這種方式轉換值,但正如我所提到的,它不會更改原始列表:
for lst in data:
for index in lst:
if index.isdigit():
index = int(index)
elif not index.isdigit():
index = float(index)
我不確定如何解決這個問題,或者是否還有另一種方法可以解決這個問題。 任何幫助,將不勝感激! 謝謝 :)
您需要使用列表訂閱更新初始索引處的項目,即在轉換項目后分配給每個索引。 您可以使用enumerate
來執行此操作,該enumerate
為列表中的每個項目提供相應的索引:
import ast
d = [['abc', '123', '45.6', 'True', 'False']]
for lst in d:
for i, x in enumerate(lst):
try:
lst[i] = ast.literal_eval(x)
except (ValueError, SyntaxError):
lst[i] = x
print(d)
# [['abc', 123, 45.6, True, False]]
ast.literal_eval
嘗試將每個字符串項解析為Python文字,如果失敗(有錯誤),則恢復為原始項(請參閱EAFP )。
如果你有大量的這些字符串,那么編寫自己的解析器會更快(盡管代碼更ast.literal_eval
,可能容易出錯),但是,讓ast.literal_eval
完成所有臟工作可能會更好。
這里沒有任何庫。 只是切片的東西和一些嘗試 - 除了技巧。 isdigit()
檢查string
是否為digit
,如果不是,則表示它是float
。 對於True
和False
,只需檢查它們是否在列表中。
這可以做得更短,我只是這樣做,所以你可以看到它是如何工作的。
all = [['abc', '123', '45.6', 'True', 'False']]
for d in all:
for x,y in enumerate(d):
if y == "True":
d[x] = True
if y == "False":
d[x] = False
for d in all:
for x,y in enumerate(d):
try:
if y.isdigit() == True:
d[x] = int(y)
else:
d[x] = float(y)
except:
pass
輸出;
['abc', 123, 45.6, True, False]
abc
<class 'str'>
123
<class 'int'>
45.6
<class 'float'>
True
<class 'bool'>
False
<class 'bool'>
試試這個(不需要圖書館):
data = [['abc', '123', '45.6', 'True', 'False']]
def isfloat(x):
try:
a = float(x)
except ValueError:
return False
else:
return True
def isint(x):
try:
a = float(x)
b = int(a)
except ValueError:
return False
else:
return a == b
for counter1, box in enumerate(data):
for counter2, items in enumerate(box):
if isfloat(items) is True:
data[counter1][counter2] = float(items)
elif isint(items) is True:
data[counter1][counter2] = float(items)
elif items == "True":
data[counter1][counter2] = True
elif items == "False":
data[counter1][counter2] = False
else:
pass
print(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.