Skip to main content
 首页 » 编程设计

python之将列表拆分为嵌套列表python

2024年10月24日12落叶

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

 ['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]] 

请您参考如下方法:

使用列表理解:

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]]