gpt4 book ai didi

python - 打印字典中最前面的 "n"个条目

转载 作者:太空狗 更新时间:2023-10-29 17:18:26 24 4
gpt4 key购买 nike

这是我当前的代码

pN ={'dave': 10, 'jacinta': 10, 'james': 8, 'john': 6, 'jack': 3, 'sam': 2}
highestCount = max(pN.values())

for k, v in pN.items():
if v == highestCount:
print(v,k)

然而,这只会打印排名靠前的用户,如果该位置是共享的,则再次打印

10 dave
10 jacinta

我需要能够打印任意数量的顶级用户 (n) 并将其格式化为这样的格式,例如对于 n = 5:

10 john, jacinta, 
8 james
6 john
3 jack
2 sam

最佳答案

使用 collections.defaultdict ,交换您的

from collections import defaultdict
dct = defaultdict(list)

for k, v in pN.items():
dct[v].append(k)

# defaultdict(<class 'list'>, {10: ['dave', 'jacinta'], 8: ['james'], 6: ['john'], 3: ['jack'], 2: ['sam']})

使用sorted 输出:

for k, v in sorted(dct.items(), reverse=True):
print(k, ', '.join(v))

# Result

10 dave, jacinta
8 james
6 john
3 jack
2 sam

函数返回前 n 用户(将并列视为一个条目):

def top_n(d, n):
dct = defaultdict(list)
for k, v in d.items():
dct[v].append(k)
return sorted(dct.items())[-n:][::-1]

top_n(pN, 3)

# [(10, ['dave', 'jacinta']), (8, ['james']), (6, ['john'])]

使用 defaultdict 既简单又快速,下面是一些时间证明:

会定时的函数

def chris_z(d, n):
dct = defaultdict(list)
for k, v in d.items():
dct[v].append(k)
return sorted(dct.items())[-n:][::-1]

def tim_lombard(score_dict, n):
lot = [(k,v) for k, v in score_dict.items()] #make list of tuple from scores dict
nl = []
while len(lot)> 0:
nl.append(max(lot, key=lambda x: x[1]))
lot.remove(nl[-1])

def ajax(d, n:'n_users', top = True):
_ranks = sorted(d.values())
_ranks = _ranks[-n:] if top else _ranks[:n]
return {i:[a for a, b in d.items() if b == i] for i in _ranks}

结果

x = [''.join(i) for i in itertools.permutations('chrisz', 6)]    
y = [random.randint(0, 100) for _ in range(720)]
z = dict(zip(x, y))

In [40]: %timeit chris_z(z, 500)
110 µs ± 259 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

In [42]: %timeit tim_lombard(z, 500)
26.2 ms ± 60 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [43]: %timeit ajax(z, 500)
15.3 ms ± 227 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

关于python - 打印字典中最前面的 "n"个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50420963/

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