gpt4 book ai didi

python - 按键分组并创建相应值的列表

转载 作者:行者123 更新时间:2023-12-04 08:31:33 25 4
gpt4 key购买 nike

我想将我的字典转换成这种格式。我曾尝试使用 groupby 但无法达到预期的格式。

input = [
{'algorithms': 'BLOWFISH', 'dcount': 5.8984375},
{'algorithms': 'AES-256', 'dcount': 5.609375},
{'algorithms': 'AES-256', 'dcount': 9.309375},
{'algorithms': 'RSA', 'dcount': 8.309375},
{'algorithms': 'BLOWFISH','dcount': 6.309375}
]
预期输出:
  output = [
{
name: "BLOWFISH",
data: [5.8984375,6.309375]
},
{
name: "AES-256",
data: [5.609375,9.309375]
},
{
name: 'RSA',
data: [8.309375]
}
]

最佳答案

您需要排序 input之前 itertools.groupby 将工作:

The operation of groupby() is similar to the uniq filter in Unix. Itgenerates a break or new group every time the value of the keyfunction changes (which is why it is usually necessary to have sortedthe data using the same key function). That behavior differs fromSQL’s GROUP BY which aggregates common elements regardless of theirinput order.

from itertools import groupby
import json

input = [
{
"algorithms": "BLOWFISH",
"dcount": 5.8984375
},
{
"algorithms": "AES-256",
"dcount": 5.609375
},
{
"algorithms": "AES-256",
"dcount": 9.309375
},
{
"algorithms": "RSA",
"dcount": 8.309375
},
{
"algorithms": "BLOWFISH",
"dcount": 6.309375
}
]

output = [
{
"name": k,
"data": [d["dcount"] for d in g]
}
for k, g in groupby(sorted(input, key=lambda d: d["algorithms"]),
key=lambda d: d["algorithms"])
]

print(json.dumps(output, indent=4))
输出:
[
{
"name": "AES-256",
"data": [
5.609375,
9.309375
]
},
{
"name": "BLOWFISH",
"data": [
5.8984375,
6.309375
]
},
{
"name": "RSA",
"data": [
8.309375
]
}
]

关于python - 按键分组并创建相应值的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64996178/

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