我编写了一个将字符串转换为数字数据类型的函数。虽然它有效,但我对代码印象不深,需要清理它。
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]
我得到了预期的输出,但我想要一些改变:
有可能吗?
答案 0 :(得分:0)
>>> 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]
的工作原理。请记住,如果将列表传递给函数,它会传入其引用,因此在函数中更改它会更改实际列表
答案 1 :(得分:0)
我认为这是一个通过将代码分解为更合乎逻辑的部分而受益的情况。您的核心任务围绕对可能是数字的各种事物执行特定操作,因此将其放在自己的函数中是有意义的。您也可以单独使用它。此外,您的测试过于复杂;没有必要测试输入是否是字符串。请考虑以下事项:
def make_numeric(thing, precision=1):
try:
return int(thing)
except ValueError:
return round(float(thing), precision)
def str_to_numeric(str_list):
for i in range(len(str_list)):
str_list[i] = make_numeric(str_list[i])
>>> k = ['1.0005','1.56666', 1, '1.2333', '1']
>>> str_to_numeric(k)
>>> k
[1.0, 1.6, 1, 1.2, 1]