我编写了一段代码,从文件中获取字符串并将其拆分为列表。但我需要将字符串拆分为嵌套的列表。
['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]]
关于python - python 将列表拆分为嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33469880/