Skip to main content
 首页 » 编程设计

python之从嵌套列表创建字典的有效方法

2025年05月04日9EasonJim

original_list = [[a,1],[a,2],[a,3],[b,5],[a,4],[b,6],[c,7],[c,8],[c,9],[c,0]] 

我有像 original_list 这样的列表。 我如何根据这样的字符对它们进行分组?

dict = {'a': [1,2,3,4], 'b':[5,6], 'c':[7,8,9,0]} 

请您参考如下方法:

根据计时结果(在下面的答案中更新)最快的方法可能是使用 collections.defaultdict .示例 -

from collections import defaultdict 
result_dic = defaultdict(list) 
for a,b in original_list: 
    result_dic[a].append(b) 

演示 -

>>> original_list = [['a',1],['a',2],['a',3],['b',5],['a',4],['b',6],['c',7],['c',8],['c',9],['c',0]] 
>>> 
>>> from collections import defaultdict 
>>> result_dic = defaultdict(list) 
>>> for a,b in original_list: 
...     result_dic[a].append(b) 
... 
>>> result_dic 
defaultdict(<class 'list'>, {'b': [5, 6], 'c': [7, 8, 9, 0], 'a': [1, 2, 3, 4]}) 

另一种方法是使用 itertools.groupby为了这。示例 -

from itertools import groupby 
result_dict = {key:list(b for a,b in group) for key,group in groupby(sorted(original_list),key=lambda x:x[0])} 

演示 -

>>> original_list = [['a',1],['a',2],['a',3],['b',5],['a',4],['b',6],['c',7],['c',8],['c',9],['c',0]] 
>>> from itertools import groupby 
>>> result_dict = {key:list(b for a,b in group) for key,group in groupby(sorted(original_list),key=lambda x:x[0])} 
>>> result_dict 
{'b': [5, 6], 'c': [0, 7, 8, 9], 'a': [1, 2, 3, 4]} 

计时结果-

In [21]: %paste 
def func1(): 
        original_list = [['a',1],['a',2],['a',3],['b',5],['a',4],['b',6],['c',7],['c',8],['c',9],['c',0]] 
        return {key:list(b for b in group) for key,group in groupby(sorted(original_list),key=lambda x:x[0])} 
 
def func2(): 
        original_list = [['a',1],['a',2],['a',3],['b',5],['a',4],['b',6],['c',7],['c',8],['c',9],['c',0]] 
        result_dic = defaultdict(list) 
        for a,b in original_list: 
                result_dic[a].append(b) 
        return result_dic 
 
def func3(): 
        original_list = [['a',1],['a',2],['a',3],['b',5],['a',4],['b',6],['c',7],['c',8],['c',9],['c',0]] 
        result = {} 
        for x in original_list: result.setdefault(x[0], []).append(x[1]) 
        return result 
 
## -- End pasted text -- 
 
In [22]: %timeit func1() 
The slowest run took 4.56 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 12.1 µs per loop 
 
In [23]: %timeit func2() 
100000 loops, best of 3: 3.82 µs per loop 
 
In [24]: %timeit func3() 
The slowest run took 4.77 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 4.31 µs per loop