我是python的初學者,如果答案很可笑,請原諒我:)
我正在嘗試撰寫一些將 str 轉換為 int 和 float 的代碼。我將在下面舉一個例子:
如果我們得到這個:
data = [['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', ' 4', '-5.0']]
我們需要回傳這個:
data = [['ab2'], [-123], ['BIKES', 3.2], [3, 4, -5]]
我已經嘗試過幾種方法來做到這一點:
# first attempt
for sublist in data:
for value in range(0, len(sublist)):
if "." in sublist[value]:
sublist[value] = float(sublist[value])
elif sublist[value].isnumeric():
sublist[value] = int(sublist[value])
# second attempt
for sublist in data:
for value in sublist:
if value.isnumeric():
if int(value) == float(value):
value = int(value)
else:
value = float(value)
不過,我不斷地回到同樣的幾個問題:
- isnumeric 或 isdigit 不接受“-”、“ ”或“.” 在答案中,所以如果我有“-123.4”那不是數字
- 像 3.0 或 4.0 這樣的數字需要轉換為整數而不是浮點數
- 我需要一種方法來改變原始串列并基本上用新數字“替換”舊數字
我知道您可以使用 try/except 塊,但我沒有研究過這些塊并且我不理解它們,所以如果有人可以給我一些關于該做什么或如何更改我的代碼的指導,將不勝感激: )
謝謝
uj5u.com熱心網友回復:
這使用正則運算式來查找有效數字。與大多數此類過濾器一樣,這會創建一個包含所需值的新串列,而不是原地寫入。
import re
nums = r"[ -]?[\d.] "
data = [['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', ' 4', '-5.0']]
newlist = []
for sublist in data:
newsub = []
for value in sublist:
if re.match( nums, value ):
if '.' not in value:
newsub.append( int(value) )
else:
value = value.rstrip('0').rstrip('.')
if '.' not in value:
newsub.append( int(value) )
else:
newsub.append( float(value) )
else:
newsub.append( value )
newlist.append( newsub )
print(newlist)
uj5u.com熱心網友回復:
使用嵌套try/ except:
def to_num(s):
# remove trailing ".0"
x = s.rstrip('0').rstrip('.') if '.' in s else s
try: # attempt int conversion
return int(x)
except ValueError:
try: # attempt float conversion
return float(x)
except ValueError:
return s # if all failed return input
[[to_num(x) for x in l] for l in data]
輸出:
[['ab2'], [-123], ['BIKES', 3.2], [3, 4, -5]]
uj5u.com熱心網友回復:
最簡單的解決方案是使用 try-except 塊。畢竟,請求寬恕比許可更容易。使用 try-except,一旦在try塊中遇到錯誤,控制就會轉移到except塊中。
在下面的示例中,如果float(value)失敗,ValueError則引發 a。此錯誤意味著該except ValueError: 塊將被執行。由于我們只想忽略錯誤,因此我們pass在except塊中。
如果沒有引發錯誤,則繼續執行下一條陳述句 ( if float_value...) 并except跳過該塊。
for sublist in data:
for index in range(len(sublist)):
value = sublist[index]
try:
float_value = float(value) # Convert to float
if float_value.is_integer(): # If successful, check if it's an integer
sublist[index] = int(float_value) # If integer, convert to integer and save the integer value
else:
sublist[index] = float_value # If not, save the float
continue # Skip the rest of the loop
except ValueError: # Catch ValueError if float() fails
pass # Do nothing if error
這使:
data = [['ab2'], [-123], ['BIKES', 3.2], [3, 4, -5]]
如果您有大整數,您可以嘗試在將其轉換為 aint 之前將其轉換為 a float,因為正如 Kelly 在他們的評論中提到的那樣,浮點數會丟失大整數的精度:
for index in range(len(sublist)):
value = sublist[index]
try:
int_value = int(value) # Convert to int
sublist[index] = int_value # If successful, save
continue # Skip the rest of the loop
except ValueError: # Catch the ValueError if int() fails
pass
# And then the try block for floats
uj5u.com熱心網友回復:
# Assuming data only contains list and in the list elements can also be list
data = [['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', ' 4', '-5.0']]
def checkPureInt(n):
n_str = str(n)
if n_str[-1] == '0' and n_str[-2] == ".":
return True
else:
return False
for i in range(len(data)):
if type(data[i]) == list:
for j in range(len(data[i])):
try:
data[i][j] = float(data[i][j])
if checkPureInt(data[i][j]):
data[i][j] = int(data[i][j])
except:
pass
print(data)
uj5u.com熱心網友回復:
import math
def is_number(string):
try:
float(string)
return True
except ValueError:
return False
data=[['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', ' 4', '-5.0']]
for i in range(len(data)):
for j in range(len(data[i])):
value=data[i][j]
if is_number(value):
if int(float(value)) == float(value):
data[i][j] = int(float(value))
#print(value)
else:
data[i][j] = float(value)
#print(value)
print(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441610.html
