gpt4 book ai didi

python - 通过字典值之一的索引将字典拆分为多个字典

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:26 26 4
gpt4 key购买 nike

data 字典拆分为与 data['legend'] 中的唯一值一样多的字典是一种优雅而有效的方法,每个字典代表传奇条目?所有列表将始终按正确顺序排列。

我目前正在使用下面的方法,但如果有更短的解决方案我很感兴趣:

data = {
'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'y': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
'legend': ["active", "pending", "pending", "active", "completed", "pending", "pending","active", "completed", "active"],
};

traces = []
unique_legend = list(set(data['legend']))
for item in unique_legend:
trace = {}
item_indices = [k for k,v in enumerate(data['legend']) if v == item]
trace['x'] = [data['x'][indice] for indice in item_indices]
trace['y'] = [data['y'][indice] for indice in item_indices]
traces.append(trace)

for trace in traces:
print(trace)

最佳答案

这是我可能采用的一种方法:

result = {}
for x in zip(data['x'], data['y'], data['legend']):
result.setdefault(x[2], []).append(x[:2])

# result will look like the following:
# {
# 'active': [(1, 10), (4, 40), (8, 80), ...],
# ...
# }

关于python - 通过字典值之一的索引将字典拆分为多个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54117563/

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