我有很多列表的长列表:
[0,['0.2000','0.2000','3.0000','0.5000']]
如何使'...'浮动并保持整数(0)整数?
我尝试过numpy,但它对我不起作用 numpy.array(list,numpy.float)
我真的不介意整数是否也是浮点数。
答案 0 :(得分:3)
我会做这样的事情:
newlist = [[element[0], [float(e) for e in element[1]] for element in oldlist]
element[0]
是保持原样的整数,element[1]
是在内部列表推导中转换为浮点数的字符串列表。
答案 1 :(得分:1)
我需要查看更多数据,以确定这是否合适,但可能会接近:
l1 = [0, ['0.2000', '0.2000', '3.0000', '0.5000']]
l2 = [x if type(x) is int else map(float, x) for x in l1]
同样,需要了解有关您的实际数据的更多信息,以确定是否有效。以上回报:
[0, [0.20000000000000001, 0.20000000000000001, 3.0, 0.5]]
答案 2 :(得分:0)
以下是你如何用numpy做到的:
In [96]: l1=[0, ['0.2000', '0.2000', '3.0000', '0.5000']]
In [97]: l2=np.array(tuple(l1),dtype=[('f1','int'),('f2','float',4)])
In [98]: l2
Out[98]:
array((0, [0.20000000000000001, 0.20000000000000001, 3.0, 0.5]),
dtype=[('f1', '<i4'), ('f2', '<f8', 4)])
如果您的实际列表看起来更像这样:
In [99]: l3=[0, ['0.2000', '0.2000', '3.0000', '0.5000'], 1, ['.1','.2','.3','0.4']]
然后你可以使用石斑鱼习语zip(*[iter(l3)]*2))
将每2个元素分组为一个元组:
In [104]: zip(*[iter(l3)]*2)
Out[104]: [(0, ['0.2000', '0.2000', '3.0000', '0.5000']), (1, ['.1', '.2', '.3', '0.4'])]
并将其传递给np.array
:
In [105]: l4=np.array(zip(*[iter(l3)]*2),dtype=[('f1','int'),('f2','float',4)])
In [106]: l4
Out[106]:
array([(0, [0.20000000000000001, 0.20000000000000001, 3.0, 0.5]),
(1, [0.10000000000000001, 0.20000000000000001, 0.29999999999999999, 0.40000000000000002])],
dtype=[('f1', '<i4'), ('f2', '<f8', 4)])
答案 3 :(得分:0)
简单地
li = [0, ['0.2000', '0.2000', '3.0000', '0.5000']]
print li
li[1] = map(float,li[1])
print li
如果 xyze 是:
xyze = [[0, ['0.2000', '0.2000', '3.000' , '0.5000']],
[9, ['0.1450', '0.8880', '3.000' , '0.4780']],
[4, ['5.0025', '7.2000', '12.00' , '6.5013']]]
DO
print '\n'.join(map(str,xyze))
print
for el in xyze:
el[1] = map(float,el[1])
print '\n'.join(map(str,xyze))
结果
[0, ['0.2000', '0.2000', '3.000', '0.5000']]
[9, ['0.1450', '0.8880', '3.000', '0.4780']]
[4, ['5.0025', '7.2000', '12.00', '6.5013']]
[0, [0.2, 0.2, 3.0, 0.5]]
[9, [0.145, 0.888, 3.0, 0.478]]
[4, [5.0025, 7.2, 12.0, 6.5013]]
答案 4 :(得分:0)
如果你想平整嵌套列表......
import types
def process(l):
for item in l:
if isinstance(item, types.ListType):
for item in process(item):
yield float(item)
else:
yield float(item)
>>> l = [0, 1, 2, [3, 4, '5.000'], ['6.01', 7, [8, 9]]]
>>> list( process(l) )
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.01, 7.0, 8.0, 9.0]