将列表拆分为嵌套列表python

时间:2015-11-02 02:33:33

标签: python nested-lists

我编写了一个代码,它从文件中获取一个字符串并将其拆分为一个列表。但我需要将字符串拆分为嵌套的列表。

 ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

 ['Acer', 'Beko', 'Cemex', 'Datsun', 'Equifax', 'Gerdau', 'Haribo']

这是输出,我试图弄清楚如何从第一个列表中获取数值数据并将其附加到名称列表,以便在下面创建嵌套的返回列表。任何想法都会很棒

[['Acer' 481242.74], ['Beko' 966071.86], ['Cemex' 187242.16], ['Datsun' 748502.91], ['Equifax' 146517.59], ['Gerdau' 898579.89], ['Haribo' 265333.85]]

1 个答案:

答案 0 :(得分:2)

使用列表理解

the_list = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

final_list = [[x.split()[0], float(x.split()[1])] for x in the_list]

print final_list

没有列表理解:

the_list = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

final_list = list()

for item in the_list:
    name = item.split()[0]
    amount = float(item.split()[1])
    final_list.append([name, amount])

print final_list

输出:

[['Acer', 481242.74], ['Beko', 966071.86], ['Cemex', 187242.16], ['Datsun', 748502.91], ['Equifax', 146517.59], ['Gerdau', 898579.89], ['Haribo', 265333.85]]