我想转换:
data = 'A|B|2|D|0.3|5|kg|1.69|m'
to list
['A','B',2,'D',0.3,5,'kg',1.69,'m']
# where every element is the type it should be (not all are strings)
我试过了:
data_list = da.split('|')
print(da_list)
['A', 'B', '2', 'D', '0.3', '5', 'kg', '1.69', 'm'] # every element is string
#Then
data_list02 = map(lambda x: (int(x) or float(x)) if x.isdigit() else str(x), data_list)
print (data_list02)
['A', 'B', 2, 'D', '0.3', 5, 'kg', '1.69', 'm'] # float are retained as str
我试过的lambda解决方案有什么问题?我不想写另一个def function
答案 0 :(得分:1)
您可以使用literal_eval
模块中的ast
使用自定义方法,例如:
from ast import literal_eval as le
def format(data, sep= '|'):
for k in data.split(sep):
try:
yield le(k)
# Or:
# You can escape any kind of odd data by using:
# except Exception:
# yield k
# Or list them then yield k
except ValueError:
yield k
# Thanks to @RomanPerekhrest's comment
except SyntaxError:
yield k
data = 'A|B|2|D|0.3|5|kg|1.69|m'
final = list(format(data))
print(final)
输出:
['A', 'B', 2, 'D', 0.3, 5, 'kg', 1.69, 'm']
PS:我没有在大量数据中测试此方法,如果任何数据失败,请留下您的反馈。
答案 1 :(得分:0)
您可以使用:
data_List=[int(x) if x.isdigit() else float(x) if x.replace(".", "", 1).isdigit() else str(x) for x in data]
示例:
>>> data = 'A|B|2|D|0.3|5|kg|1.69|m'
>>> data=data.split('|')
>>> data
['A', 'B', '2', 'D', '0.3', '5', 'kg', '1.69', 'm']
>>> data_List=[int(x) if x.isdigit() else float(x) if x.replace(".", "", 1).isdigit() else str(x) for x in data]
>>> data_List
['A', 'B', 2, 'D', 0.3, 5, 'kg', 1.69, 'm']
<强> 修改 强>
如果您使用负整数或浮点数:
data_List=[int(x) if x.lstrip('-').isdigit() else float(x) if x.lstrip('-').replace(".", "", 1).isdigit() else str(x) for x in data]
示例:
>>> data = 'A|B|2|D|0.3|-5|kg|-1.69|m'
>>> data=data.split('|')
>>> data_List=[int(x) if x.lstrip('-').isdigit() else float(x) if x.lstrip('-').replace(".", "", 1).isdigit() else str(x) for x in data]
>>> data_list
['A', 'B', 2, 'D', 0.3, -5, 'kg', -1.69, 'm']