2016-03-15 88 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]] 
]