dws*_*ein 6 python dictionary list python-2.7
如果我有一个dict列表,如:
{
'id1': ['a', 'b', 'c'],
'id2': ['a', 'b'],
# etc.
}
Run Code Online (Sandbox Code Playgroud)
我想计算清单的大小,即.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
Run Code Online (Sandbox Code Playgroud)
我会使用一个collections.Counter()对象来收集长度,然后累加总和:
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
Run Code Online (Sandbox Code Playgroud)
因此,这会收集每个长度的计数,然后构建一个具有累积长度的字典。这是一个 O(N) 算法;您对所有值进行一次循环,然后添加一些较小的直循环(formax()和累积循环):
>>> 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}
Run Code Online (Sandbox Code Playgroud)