gpt4 book ai didi

python - 优化创建字典

转载 作者:太空宇宙 更新时间:2023-11-03 14:52:13 25 4
gpt4 key购买 nike

我有一个名为 ids 的 id 列表。 ids 中的每个元素都是一个字符串。一个 id 可以在此列表中多次存在。

我的目标是创建一个字典,它以出现次数为键,值是经常出现的 ID 列表。我目前的做法是这样的:

from collections import defaultdict
import numpy as np
ids = ["foo", "foo", "bar", "hi", "hi"]
counts = defaultdict(list)
for id in np.unique(ids):
counts[ids.count(id)].append(id)

输出:

print counts
--> defaultdict(<type 'list'>, {1: ['bar'], 2: ['foo', 'hi']})

如果 id 列表不太长,这会很好地工作。但是,对于较长的列表,性能会很差。

我怎样才能让它更快?

最佳答案

不是为列表中的每个元素调用 count,而是创建一个 collections.Counter对于整个列表:

ids = ["foo", "foo", "bar", "hi", "hi"]
counts = defaultdict(list)
for i, c in Counter(ids).items():
counts[c].append(i)
# counts: defaultdict(<class 'list'>, {1: ['bar'], 2: ['foo', 'hi']})

如果您更喜欢单行,您也可以结合使用 Counter.most_common (用于查看按计数排序的元素)和 itertools.groupby (但我宁愿不这样做)

>>> {k: [v[0] for v in g] for k, g in groupby(Counter(ids).most_common(), lambda x: x[1])}
{1: ['bar'], 2: ['foo', 'hi']}

关于python - 优化创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076268/

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