2015-11-02 44 views
2

我已經編寫了一個代碼,該代碼從文件中獲取一個字符串並將其拆分爲一個列表。但我需要將字符串拆分爲嵌套的列表。將列表拆分爲嵌套列表python

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

回答

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