[英]Convert empty strings of a list to float
我有一個這樣的字符串列表:
grades = [['2.0', '3.67', '3.67', '2.33', '3.67', '2.0', '3.67', '2.33', '3.0', '2.33', '', '3.67', '2.33', '2.67', '3.0', '2.0', '4.0', '3.33', '4.0'],[...]]
它包含成績,但也有空項目。 當我將它轉換為浮動時,它會刪除那些空的。
我要做的是:
def try_convert(val):
try:
return float(val)
except ValueError as TypeError:
pass
floatGrades = [[float(z) for z in (try_convert(j) for j in i) if z] for i in grades]
有沒有辦法將這樣的空字符串變成 0?或無?
我更喜歡使用 function 來檢查是否可能。 這樣您就可以使 function 更通用; 一般用途:
grades = [['2.0', '3.67', '3.67', '2.33', '3.67', '2.0', '3.67', '2.33', '3.0', '2.33', '', '3.67', '2.33', '2.67', '3.0', '2.0', '4.0', '3.33', '4.0']]
def try_convert(val):
try:
float(val)
return True
except ValueError:
return False
# Get only values that can convert to float
result = [float(x) for values in grades for x in values if try_convert(x) == True]
# When can convert float(value) else None
result = [float(x) if try_convert(x) == True else None for values in grades for x in values ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.