【发布时间】:2021-02-24 23:57:40
【问题描述】:
我的代码可以根据字符串本身将字符串转换为整数或浮点数。
def convert_data(data: List[List[str]]) -> None:
for sublist in data: #Accesses each element in data
for index, element in enumerate(sublist):
if element.isnumeric(): #If element is a number, check to see if it can be an int
sublist[index] = int(element) #Convert to an int
elif element.replace('.', '').isnumeric(): #If element is a number, check to see if it can be a float
sublist[index] = float(element) #convert to a float
else:
sublist[index] = sublist[index] #If it isn't a number, return the string as it is
our_data = [['no'], ['-123'], ['+5.6', '3.2'], ['3.0', '+4', '-5.0']]
convert_data(our_data)
函数运行后,our_data 应该是:
[['no'], [-123], [5.6, 3.2], [3, 4, -5]]
但是,我得到:
[['no'], ['-123'], ['+5.6', 3.2], [3.0, '+4', '-5.0']]
我需要这样做,以便它将带有“+”或“-”的任何内容转换为整数/浮点数,而不是将其作为字符串返回。我该怎么做?
如果您认为我的代码混乱,我深表歉意,我只是在快速尝试解决我遇到的这个问题。感谢您的帮助!
【问题讨论】:
-
eval()可以解决这个问题
标签: python python-3.x list integer