Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过字典'之一的索引将字典拆分为多个字典;s值_Python - Fatal编程技术网

Python 通过字典'之一的索引将字典拆分为多个字典;s值

Python 通过字典'之一的索引将字典拆分为多个字典;s值,python,Python,如果要将数据字典拆分为多个字典,并且数据['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",

如果要将
数据
字典拆分为多个字典,并且
数据['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), ...],
#    ...
# }

如果我理解正确,看起来您正在尝试获取与
图例
条目对应的
列表
s的
x
y
。您可以使用
zip
收集所有信息。注意,这需要
len(x)==len(y)==len(图例)


我邀请您与熊猫见面,熊猫简化了这些频繁的需求:

import pandas as pd
df=pd.DataFrame(data).set_index("legend").sort_index()
print(df)
            x    y
legend            
active      1   10
active      4   40
active      8   80
active     10  100
completed   5   50
completed   9   90
pending     2   20
pending     3   30
pending     6   60
pending     7   70
这样就可以轻松访问所有子部件:

>>> df.loc['active','x']

legend
active     1
active     4
active     8
active    10
Name: x, dtype: int64  
您可以返回到更熟悉的表单:

>>> { leg:{ key:list(df.loc[leg,key]) for key in df.columns} for leg in df.index.unique()}  

{'active': {'x': [1, 4, 8, 10], 'y': [10, 40, 80, 100]},
 'completed': {'x': [5, 9], 'y': [50, 90]},
 'pending': {'x': [2, 3, 6, 7], 'y': [20, 30, 60, 70]}}
以下是我得到的:

from itertools import groupby
from collections import namedtuple

dtype = namedtuple('dtype', ['legend', 'x', 'y'])
sorted_legends = sorted((dtype(*l) for l in zip(data['legend'], data['x'], 
    data['y'])))

for k,v in groupby(sorted_legends, key=lambda x:x.legend):
    x, y = [], []
    for i in v:
        x.append(i[1])
        y.append(i[2])
    print({'x': x, 'y': y})

我使用了一个非常适合于可维护代码的字典(对于您的请求可能有点过分)。

字典的目的是显示特定图例状态(活动)的所有(x,y)吗?
from itertools import groupby
from collections import namedtuple

dtype = namedtuple('dtype', ['legend', 'x', 'y'])
sorted_legends = sorted((dtype(*l) for l in zip(data['legend'], data['x'], 
    data['y'])))

for k,v in groupby(sorted_legends, key=lambda x:x.legend):
    x, y = [], []
    for i in v:
        x.append(i[1])
        y.append(i[2])
    print({'x': x, 'y': y})