更改嵌套列表

时间:2017-11-25 11:49:36

标签: python list floating-point nested-lists

我是python的新手,我现在面临一个小小的挑战 我有这个清单nested_list = [['1','2','3'],['2','4','6']] 我想将列表的字符串更改为其浮点表示 同时保持订单相同

new_list = [[1.0,2.0,3.0],[2.0,4.0,6.0]]

感谢您的帮助

4 个答案:

答案 0 :(得分:1)

为每个嵌套列表中的每个项目调用new_list = [[float(x) for x in lst] for lst in nested_list]

var draggie = new Draggabilly(gridItem, {
  axis:'x'
});

答案 1 :(得分:1)

也可以在嵌套列表上使用map完成:

new_list = [list(map(float, lst)) for lst in nested_list]

答案 2 :(得分:0)

如果您已经安装了numpy模块,可以像下面这样写。在此代码for-loop中不存在。您不想仅为此安装numpy模块......

import numpy as np
nested_list = [['1','2','3'],['2','4','6']]
new_lst = np.array(nested_list, dtype=np.float).tolist()

答案 3 :(得分:-1)

使用两个循环不是这个小任务的好选择,导入任何外部模块也不是一个好选择:

  

没有任何循环的一行解决方案:

nested_list = [['1','2','3'],['2','4','6']]

print(list(map(lambda x:list(map(lambda y:float(y),x)),nested_list)))
  

输出:

[[1.0, 2.0, 3.0], [2.0, 4.0, 6.0]]