我有这样的数据
["0:0:0.123", "1:0:0.345", "2:0:0.675"]
然后我想把它转换成像这样的正式
[[0,0,0.123], [1,0,0.345], [2,0,0.675]]
任何建议将不胜感激。数据规模越大,效率越高越好。
答案 0 :(得分:2)
a = ["0:0:0.123", "1:0:0.345", "2:0:0.675"]
b = [ [float(d) for d in c.split(':')] for c in a ]
print( b )
可生产
[[0.0, 0.0, 0.123], [1.0, 0.0, 0.345], [2.0, 0.0, 0.675]]
如果您特别想要字符串为整数的整数,则可以这样做,
a = ["0:0:0.123", "1:0:0.345", "2:0:0.675"]
b = [ [ ( float(d) if '.' in d else int(d) ) for d in c.split(':')] for c in a ]
print(b)
产生
[[0, 0, 0.123], [1, 0, 0.345], [2, 0, 0.675]]
或者,如果你想使用try - except,你可以定义一个函数来解析字符串,
def myparse(a):
try:
return int(a)
except:
return float(a)
然后
a = ["0:0:0.123", "1:0:0.345", "2:0:0.675"]
b = [ [myparse(d) for d in c.split(':')] for c in a ]
print(b)
再次产生
[[0, 0, 0.123], [1, 0, 0.345], [2, 0, 0.675]]
QED