Python:根据另一个列表将列表拆分为较小的jsons

时间:2015-12-03 11:37:46

标签: python list python-3.x

我有一个程序名列表,需要根据优先级列表分类到较小的jsons列表中。我需要在python 3中执行此操作。 B和C具有相同的优先级2,它们将一起列在一个列表中。

program_names = ['A','B','C','D']
priorities = [1,2,2,3]

必需的最终结果:

[[{"name": "A"}], [{"name":"B"}, {"name":"C"}], [{"name":"D"}]]

当前代码:

program_names_list = []
    final_list = []
    for x in program_names.split(','):
        program_names_list.append(x)
    for x in program_names_list:
        final_list.append([{"name": x}])

这就是我目前所拥有的输出以下结果:

[[{'name': 'A'}], [{'name': 'B'}], [{'name': 'C'}], [{'name': 'D'}]]

我应该补充一点,program_names是一个字符串“A,B,C,D”

4 个答案:

答案 0 :(得分:2)

完整解决方案

items = {}
for k, v in zip(priorities, program_names):
    items.setdefault(k, []).append(v)
[[{'name': name} for name in items[key]] for key in sorted(items.keys())]

返回:

[[{'name': 'A'}], [{'name': 'B'}, {'name': 'C'}], [{'name': 'D'}]]    

步骤

创建一个字典,该字典使用优先级作为键,并列出所有具有相应优先级的程序名称作为值:

items = {}
for k, v in zip(priorities, program_names):
    items.setdefault(k, []).append(v)

浏览已排序的密钥,并通过密钥从字典中获取它们来创建一个新的程序名列表:

[[{'name': name} for name in items[key]] for key in sorted(items.keys())]

答案 1 :(得分:2)

循环优先级并使用优先级作为键的字典和程序列表作为值来对具有相同优先级的所有元素进行分组。

In [24]: from collections import defaultdict

In [25]: program_names = ['A','B','C','D']

In [26]: priorities = [1,2,2,3]

In [27]: d = defaultdict(list)

In [28]: for i, p in enumerate(sorted(priorities)):
    d[p].append({'name': program_names[i]})
   ....:

In [29]: list(d.values())
Out[29]: [[{'name': 'A'}], [{'name': 'B'}, {'name': 'C'}], [{'name': 'D'}]]

答案 2 :(得分:1)

虽然从教育的角度来看这可能是错的,但我无法拒绝单行回答这些问题:

[[{'name': p_n} for p_i, p_n in zip(priorities, program_names) if p_i == p] for p in sorted(set(priorities))]

(这假设您的“优先级”列表可能会被排序,并且效率低于使用defaultdict(list)的“正常”方法。

更新:借用damn_c-s的回答,这是一个有效的单行(不计算隐含的from itertools import groupby):

[[{'name': pn} for pi, pn in l] for v, l in groupby(zip(priorities, program_names), lambda x: x[0])]

答案 3 :(得分:1)

使用groupby。

from itertools import groupby

program_names = ['a','b','c','d']
priorities = [1,2,2,3]

data = zip(priorities, program_names)

groups_dict = []
for k, g in groupby(data, lambda x: x[0]):
    m = map(lambda x: dict(name=x[1]), list(g))
    groups_dict.append(m)

print(groups_dict)