gpt4 book ai didi

python - 在一个列表中存储多个整数值并返回最佳值对

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

我有以下三个整数值:

id        # identifies the pair
entropy # gives entropy information
len # basicly the length of a string

现在我想存储这些值中的许多值,并选择总熵最高且长度值超过 n

的前 10 个值
from collections import defaultdict

d = defaultdict(list)

for id, entropy, len in generateValues:
d[id].append(entropy)
d[id].append(len)

# now get the top 10 values

这很容易做到吗?

最佳答案

像这样构建字典后,您可以获得前 10 个值。尽管如果可能的话,如果您在构建字典时找到它们,将会有更有效的解决方案。

import heapq
heapq.nlargest(10, (k for k in d if d[k][1] > n), key=lambda k: d[k][0])

关于python - 在一个列表中存储多个整数值并返回最佳值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16565634/

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