gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:00:24 25 4
gpt4 key购买 nike

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

关于python - 从嵌套列表创建字典的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33033299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com