我有一个看起来像这样的元组列表;
li = [('Replicate 1', '_E748_.txt'),
('Replicate 1', '_E749_.txt'),
('Replicate 2', '_E758_.txt'),
('Replicate 2', '_E759_.txt')]
创建看起来像这样的字典的最快方法是什么;
{'Replicate1': ['_E748_.txt', '_E749_.txt'],
'Replicate2': ['_E758_.txt', '_E759_.txt']}
答案 0 :(得分:4)
鉴于
>>> li = [('Replicate 1', '_E748_.txt'),
... ('Replicate 1', '_E749_.txt'),
... ('Replicate 2', '_E758_.txt'),
... ('Replicate 2', '_E759_.txt')]
待办事项
>>> d = {}
>>> for k, v in li:
... d.setdefault(k, []).append(v)
...
>>> d
{'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']}
或者
>>> from collections import defaultdict
>>> d2 = defaultdict(list)
>>> for k, v in li:
... d2[k].append(v)
...
>>> d2
defaultdict(<type 'list'>, {'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']})
甚至是过于花哨的
>>> from itertools import groupby
>>> from operator import itemgetter
>>> get0, get1 = itemgetter(0), itemgetter(1)
>>> dict((key, list(map(get1, subit))) for key, subit in groupby(sorted(li), get0))
{'Replicate 2': ['_E758_.txt', '_E759_.txt'], 'Replicate 1': ['_E748_.txt', '_E749_.txt']}