给定一个嵌套的元组列表(这是第0个元素上itertools.groupby
操作的输出:
l = [[(95, 'studentD')], [(97, 'studentB')], [(98, 'studentA'), (98, 'studentC')]]
有一种简单的方法可以获得这个吗?
{ 95 : 'studentD', 97 : 'studentB', 98: ['studentA', 'studentC']}
注意单个元素不会放在列表中。此外,我可以保证内部列表中的所有元组具有相同的x[0]
。
这是我的解决方案:
In [203]: d = {}
In [204]: for x in l:
...: d.update({x[0][0] : ([y for _, y in x] if len(x) > 1 else x[0][1]) })
...:
In [205]: d
Out[205]: {95: 'studentD', 97: 'studentB', 98: ['studentA', 'studentC']}
我缺少更优雅的选择吗?
答案 0 :(得分:2)
最好直接从itertools.groupby
的结果进行分组,而不是尝试将整个结果重新处理成dict。
从原始问题的副本开始:
from itertools import groupby
l = [(95, 'studentD'), (97, 'studentB'), (98, 'studentA'), (98, 'studentC')]
d = {}
for k, g in groupby(l, lambda x: x[0]):
g = [x for _, x in g]
d[k] = g[0] if len(g) == 1 else g
print d
# {97: 'studentB', 98: ['studentA', 'studentC'], 95: 'studentD'}
答案 1 :(得分:1)
如果你必须重新加工,并且正在寻找优雅的,如果不是Pythonic,那该怎么样:
car
但如果我们回到Car
步骤,我们可以做一些令人讨厌的事情,如:
>>> l = [[(95, 'studentD')], [(97, 'studentB')], [(98, 'studentA'), (98, 'studentC')]]
>>>
>>> d = {}
>>>
>>> for x in l:
... grades, students = zip(*x)
... d[grades[0]] = students if len(students) > 1 else students[0]
...
>>> print(d)
{95: 'studentD', 97: 'studentB', 98: ('studentA', 'studentC')}
>>> ^D
使用赋值结构来简化触摸。
答案 2 :(得分:0)
以下是使用groupby
import collections
l = [(95, 'studentD'), (97, 'studentB'), (98, 'studentA'), (98, 'studentC')]
result_dict = collections.defaultdict(list)
for x, y in l:
result_dict[x].append(y)
答案 3 :(得分:0)
如果您接受所有项目都在列表中: Flatten + defaultdict
from collections import defaultdict
l = [[(95, 'studentD')], [(97, 'studentB')], [(98, 'studentA'), (98, 'studentC')]]
flat = tuple(item for sublist in l for item in sublist)
d = defaultdict(list)
for k,v in flat:
d[k].append(v)
给出:
defaultdict(list,
{95: ['studentD'], 97: ['studentB'], 98: ['studentA', 'studentC']})
可以删除那些:
for k,v in d.items():
if len(v) == 1:
d[k] = v[0]
答案 4 :(得分:-5)
L = [[(95, 'studentD')], [(97, 'studentB')], [(98, 'studentA'), (98, 'studentC')]]
answer = {}
for subl in L:
for grade, student in subl:
if grade not in answer:
answer[grade] = []
answer[grad].append(student)