我编写了一个将字符串转换为数字数据类型的函数。尽管它可以正常工作,但是我对代码没有印象,需要清理它。
def str_to_numeric(str_list):
"""
modify elements of list received from file to numeric data
type.
"""
temp_list = []
for item in str_list:
if type(item) == str:
try:
temp_list.append(int(item))
except:
temp_list.append(round(float(item), 1))
elif type(item) == float:
temp_list.append(round(float(item), 1))
else:
temp_list.append(item)
str_list = temp_list
return str_list
List1 = ['1.0005','1.56666', 1, '1.2333', '1']
List1 = str_to_numeric(List1)
Output: [1.0, 1.6, 1, 1.2, 1]
我正在获得预期的输出,但是我需要一些更改:
可能吗?
>>> def str_to_numeric(str_list):
"""
modify elements of list received from file to numeric data
type.
"""
for i,item in enumerate(_ for _ in str_list):
if type(item) == str:
try:
str_list[i] = int(item)
except:
str_list[i]=round(float(item), 1)
elif type(item) == float:
str_list[i] = round(float(item), 1)
else:
str_list[i]=item
>>> List1 = ['1.0005','1.56666', 1, '1.2333', '1']
>>> str_to_numeric(List1)
>>> List1
[1.0, 1.6, 1, 1.2, 1]
作品。请记住,如果将列表传递给函数,则它会传递其引用,因此在函数中对其进行更改会更改实际的列表
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句