2014-10-04 128 views
-3

我的列表:如何按索引連接列表中的元素?

['0.125', '0', 'A'] 
['0.5', '0', 'B', ' A'] 
['0.75', '0', 'C'] 
['0.5', '0.5', 'D', ' C', 'A'] 

我想

['0.125', '0', 'A'] 
['0.5', '0', 'B'] 
['0.5', '0', 'A'] 
['0.75', '0', 'C'] 
['0.5', '0.5', 'D'] 
['0.5', '0.5', 'C'] 
['0.5', '0.5', 'A'] 

這樣做的任何指南?

回答

2

您可以使用嵌套列表理解:

[sub[:2] + [elem] for sub in yourlist for elem in sub[2:]] 

演示:

>>> yourlist = [ 
...  ['0.125', '0', 'A'], 
...  ['0.5', '0', 'B', ' A'], 
...  ['0.75', '0', 'C'], 
...  ['0.5', '0.5', 'D', ' C', 'A'], 
... ] 
>>> from pprint import pprint 
>>> [sub[:2] + [elem] for sub in yourlist for elem in sub[2:]] 
[['0.125', '0', 'A'], ['0.5', '0', 'B'], ['0.5', '0', ' A'], ['0.75', '0', 'C'], ['0.5', '0.5', 'D'], ['0.5', '0.5', ' C'], ['0.5', '0.5', 'A']] 
>>> pprint(_) 
[['0.125', '0', 'A'], 
['0.5', '0', 'B'], 
['0.5', '0', ' A'], 
['0.75', '0', 'C'], 
['0.5', '0.5', 'D'], 
['0.5', '0.5', ' C'], 
['0.5', '0.5', 'A']] 
+1

我得到這個錯誤「類型錯誤:不能連接‘海峽’和‘名單’的對象」,請建議。 – ThanaDaray 2014-10-04 08:45:51

+0

@ThanaDaray:我會添加一個演示; 'yourlist'是所有輸入列表的列表,而不是單個列表。 – 2014-10-04 08:47:08

相關問題