gpt4 book ai didi

python - 用于在 Python 中更新共享字典的多处理模块

转载 作者:太空狗 更新时间:2023-10-30 00:02:14 25 4
gpt4 key购买 nike

我正在创建一个字典,如下所示:

y=[(1,2),(2,3),(1,2),(5,6)]

dict={}

for tup in y:
tup=tuple(sorted(tup))
if tup in dict.keys():
dict[tup]=dict[tup]+1
else:
dict[tup]=1

但是我的实际 y 包含大约 4000 万个元组,有没有办法使用多处理来加速这个过程?

谢谢

最佳答案

如果你想得到忽略顺序的计数,使用带有计数器的frozenset:

from collections import Counter

print(Counter(map(frozenset, y)))

使用来自另一个答案的元组:

In [9]: len(tuples)
Out[9]: 500000

In [10]: timeit Counter(map(frozenset, tuples))
1 loops, best of 3: 582 ms per loop

使用 frozenset 意味着 (1, 2)(2,1) 将被认为是相同的:

In [12]: y = [(1, 2), (2, 3), (1, 2), (5, 6),(2, 1),(6,5)]

In [13]: from collections import Counter

In [14]:

In [14]: print(Counter(map(frozenset, y)))
Counter({frozenset({1, 2}): 3, frozenset({5, 6}): 2, frozenset({2, 3}): 1})

如果您使用多处理应用相同的逻辑,它显然会快得多,即使没有它也比使用多处理提供的更快。

关于python - 用于在 Python 中更新共享字典的多处理模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34220833/

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