2016-03-15 86 views
0

我有一個例子多維列表:在python中從mutidimentioal列表創建多維列表?

example_list=[ 
     ["a","b","c", 2,4,5,7], 
     ["e","f","g",0,0,1,5], 
     ["e","f","g", 1,4,5,7], 
     ["a","b","c", 3,2,5,7] 
    ] 

怎麼可能把他們在羣體像這樣:

out_list=[ 
     [["a","b","c", 2,4,5,7], 
      ["a","b","c",3,2,5,7] 
     ], 
     [["e","f","g", 0,0,1,5], 
      ["e","f","g", 1,4,5,7] 
     ] 
] 

我已經試過這樣:

example_list=[["a","b","c", 2,4,5,7],["e","f","g", 0,0,1,5],["e","f","g",1,4,5,7],["a","b","c", 3,2,5,7]] 
unique=[] 
index=0 
for i in range(len(example_list)): 
    newlist=[] 
    if example_list[i][:3]==example_list[index][:3]: 
     newlist.append(example_list[i]) 
    index=index+1 
    unique.append(newlist)    
print unique 

我的結果是這個:

[['a','b','c',2,4,5,7]],[['e',' 'f','g',0,0,1,5]],[['e','f','g',1,4,5,7]],[['a','b ','c',3,2,5,7]]]

我想不起來。 請幫忙。 謝謝, Shiuli

+0

取決於三個第一要素分組? – YOBA

回答

0

如果分組是通過下面的代碼在每個列表中的前三個要素決定會做什麼你問了:

from collections import defaultdict 

example_list=[["a","b","c", 2,4,5,7],["e","f","g",0,0,1,5],["e","f","g", 1,4,5,7],["a","b","c", 3,2,5,7]] 
d = defaultdict(list) 
for l in example_list: 
    d[tuple(l[:3])].append(l) 

print d.values() # [[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], ...] 

這將使用defaultdict生成一個字典,其中鍵是前三個元素,值是以這些元素開頭的列表的列表。

0

首先簡單地使用sorted()對列表進行排序,提供lambda函數作爲關鍵字。

>>> a = sorted(example_list, key=lambda x:x[:3]) 
[['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7], ['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]] 

然後排序列表上使用itertools.groupby()

>>> [list(v) for k, v in groupby(a, lambda x:x[:3])] 
[ 
    [['a', 'b', 'c', 2, 4, 5, 7], ['a', 'b', 'c', 3, 2, 5, 7]], 
    [['e', 'f', 'g', 0, 0, 1, 5], ['e', 'f', 'g', 1, 4, 5, 7]] 
]