按列表中的键组合元素

时间:2016-02-11 05:29:43

标签: python list-comprehension

我有以下列表

some_list = [{'key': 'YOUNG', 'x': 22, 'y': 0.9},
             {'key': 'OLD', 'x': 45, 'y': 0.6},
             {'key': 'OLD', 'x': 40, 'y': 0.3},
             {'key': 'YOUNG', 'x': 25, 'y': 0.3}]

我想将其更改为:

[{'key': 'YOUNG', 'values': [ {'x': 25, 'y': 0.3}, {'x': 22, 'y': 0.9} ]}
 {'key': 'OLD', 'values': [ {'x': 40, 'y': 0.3}, {'x': 45, 'y': 0.6} ]}]

我添加了一些尝试

arr = [{'key': 'YOUNG', 'x': 22, 'y': 0.9},
       {'key': 'OLD', 'x': 45, 'y': 0.6},
       {'key': 'OLD', 'x': 40, 'y': 0.3},
       {'key': 'YOUNG', 'x': 25, 'y': 0.3}]

all_keys = []
for item in arr:
   all_keys.append(item['key'])

all_keys = list(set(all_keys))

res = [[{
         'key': key,
         'values': {'x': each['x'], 'y': each['y']}
        } for each in arr if each['key'] == key]
       for key in all_keys]

print res       

但结果不对,它构建了更多列表: [[{'values':{'y':0.6,'x':45},'key':'OLD'},{'values':{'y':0.3,'x':40},' key':'OLD'}],[{'values':{'y':0.9,'x':22},'key':'YOUNG'},{'values':{'y':0.3, 'x':25},'key':'YOUNG'}]]

感谢。

7 个答案:

答案 0 :(得分:3)

循环应该是这样的:

res = [{ 'key': key,
         'values': [{'x': each['x'], 'y': each['y']} 
                    for each in arr if each['key'] == key] }
       for key in all_keys]

答案 1 :(得分:1)

使用中间字典,您可以这样做:

>>> temp_data = {}
>>> for x in some_list:
...     temp_data.setdefault(x['key'], []).append({k: x[k] for k in ['x', 'y']})
>>> [{'key': k, 'values': v} for k,v in temp_data.items()]
[{'key': 'OLD', 'values': [{'x': 45, 'y': 0.6}, {'x': 40, 'y': 0.3}]},
 {'key': 'YOUNG', 'values': [{'x': 22, 'y': 0.9}, {'x': 25, 'y': 0.3}]}]

虽然我个人想把它留在字典中:

>>> temp_data
{'OLD': [{'x': 45, 'y': 0.6}, {'x': 40, 'y': 0.3}],
 'YOUNG': [{'x': 22, 'y': 0.9}, {'x': 25, 'y': 0.3}]}

答案 2 :(得分:0)

另一种尝试可能是使用defaultdict - 如果数据较大,它会运行得更快。

from collections import defaultdict

data = defaultdict(list)
some_list = [{'key': 'YOUNG', 'x': 22, 'y': 0.9},
             {'key': 'OLD', 'x': 45, 'y': 0.6},
             {'key': 'OLD', 'x': 40, 'y': 0.3},
             {'key': 'YOUNG', 'x': 25, 'y': 0.3}]


for item in some_list:
    vals = item.copy()
    del vals['key']
    data[item['key']].append(vals)

print [{'key':k,'values':v} for k,v in data.items()]

输出(字典不关心排序) -

[{'values': [{'y': 0.6, 'x': 45}, {'y': 0.3, 'x': 40}], 'key': 'OLD'}, {'values': [{'y': 0.9, 'x': 22}, {'y': 0.3, 'x': 25}], 'key': 'YOUNG'}]

答案 3 :(得分:0)

from  itertools import *
data =  [{'key': 'YOUNG', 'x': 22, 'y': 0.9},
             {'key': 'OLD', 'x': 45, 'y': 0.6},
             {'key': 'OLD', 'x': 40, 'y': 0.3},
             {'key': 'YOUNG', 'x': 25, 'y': 0.3}]
data = sorted(data, key=lambda x: x['key'])
groups = []
uniquekeys = []

for k, v in groupby(data, lambda x: x['key'] ):
    val_list = []
    for each_val in v:
        val_list.append({ 'x' : each_val['x'], 'y': each_val['y']})
    groups.append(val_list)
    uniquekeys.append(k)

print uniquekeys
print groups
print zip(uniquekeys, groups)

您将输出作为元组列表,其中第一个元素是您的键,第二个元素是组/值列表,

[('OLD', [{'y': 0.6, 'x': 45}, {'y': 0.3, 'x': 40}]), ('YOUNG', [{'y': 0.9, 'x': 22}, {'y': 0.3, 'x': 25}])]

答案 4 :(得分:0)

some_list = [{'key': 'YOUNG', 'x': 22, 'y': 0.9},
             {'key': 'OLD', 'x': 45, 'y': 0.6},
             {'key': 'OLD', 'x': 40, 'y': 0.3},
             {'key': 'YOUNG', 'x': 25, 'y': 0.3}]

outDict = {}

for dictionary in some_list:
    key = dictionary['key']
    copyDict = dictionary.copy()    #This leaves the original dict list unaltered
    del copyDict['key']
    if key in outDict:
        outDict[key].append(copyDict)
    else:
        outDict[key] = [copyDict]

print(outDict)
print(some_list)

答案 5 :(得分:0)

你去吧 -

some_list = [{'key': 'YOUNG', 'x': 22, 'y': 0.9},
             {'key': 'OLD', 'x': 45, 'y': 0.6},
             {'key': 'OLD', 'x': 40, 'y': 0.3},
             {'key': 'YOUNG', 'x': 25, 'y': 0.3}]

dict_young_vals = []
dict_old_vals = []
for dict_step in some_list:
  temp_dict = {}
  if (dict_step['key'] == 'YOUNG'):
    for keys in dict_step.keys():
      if keys != 'key':
        temp_dict[keys] = dict_step[keys]
    if temp_dict != {}:
      dict_young_vals.append(temp_dict)
  if (dict_step['key'] == 'OLD'):
    for keys in dict_step.keys():
      if keys != 'key':
        temp_dict[keys] = dict_step[keys]
    if temp_dict != {}:
      dict_old_vals.append(temp_dict)


dict_young = {'key':'YOUNG'}
dict_young['values'] = dict_young_vals
dict_old = {'key': 'OLD'}
dict_old['values'] = dict_old_vals
print(dict_young_vals)
result_dict = []
result_dict.append(dict_young)
result_dict.append(dict_old)
print(result_dict)

答案 6 :(得分:0)

some_list = [{'key': 'YOUNG', 'x': 22, 'y': 0.9},
         {'key': 'OLD', 'x': 45, 'y': 0.6},
         {'key': 'OLD', 'x': 40, 'y': 0.3},
         {'key': 'YOUNG', 'x': 25, 'y': 0.3}]

x=[]

for i in some_list:
    d={}
    d["key"]=i["key"]
    d["values"]=[{m:n for m,n in i.items() if m!="key"}]
    if d["key"] not in [j["key"] for j in x]:
        x.append(d)
    else:
        for k in x:
            if k["key"]==d["key"]:
                k["values"].append(d["values"][0])
print x

输出:[{'values': [{'y': 0.9, 'x': 22}, {'y': 0.3, 'x': 25}], 'key': 'YOUNG'}, {'values': [{'y': 0.6, 'x': 45}, {'y': 0.3, 'x': 40}], 'key': 'OLD'}]