gpt4 book ai didi

python - 如何用字典计算列表的大小?

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

如果我有一个 dict 列表,例如:

{
'id1': ['a', 'b', 'c'],
'id2': ['a', 'b'],
# etc.
}

我想计算列表的大小,即 id >0、>1、>2...等的数量

有没有比这样的嵌套 for 循环更简单的方法:

dictOfOutputs = {}
for x in range(1,11):
count = 0
for agentId in userIdDict:
if len(userIdDict[agentId]) > x:
count += 1
dictOfOutputs[x] = count
return dictOfOutputs

最佳答案

我会使用 collections.Counter() object收集长度,然后累加和:

from collections import Counter

lengths = Counter(len(v) for v in userIdDict.values())
total = 0
accumulated = {}
for length in range(max(lengths), -1, -1):
count = lengths.get(length, 0)
total += count
accumulated[length] = total

所以这会收集每个长度的计数,然后构建一个具有累积长度的字典。这是一个 O(N) 算法;你遍历所有值一次,然后添加一些更小的直接循环(对于 max() 和累加循环):

>>> from collections import Counter
>>> import random
>>> testdata = {''.join(random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(5)): [None] * random.randint(1, 10) for _ in range(100)}
>>> lengths = Counter(len(v) for v in testdata.values())
>>> lengths
Counter({8: 14, 7: 13, 2: 11, 3: 10, 4: 9, 5: 9, 9: 9, 10: 9, 1: 8, 6: 8})
>>> total = 0
>>> accumulated = {}
>>> for length in range(max(lengths), -1, -1):
... count = lengths.get(length, 0)
... total += count
... accumulated[length] = total
...
>>> accumulated
{0: 100, 1: 100, 2: 92, 3: 81, 4: 71, 5: 62, 6: 53, 7: 45, 8: 32, 9: 18, 10: 9}

关于python - 如何用字典计算列表的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30172975/

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