单行创建列表字典

Lia*_*odi 5 python

如何做这个列表/字典理解把这个 [("a", 1), ("b", 2), ("a", 3)]

进入这个

{
  "a": [1, 3],
  "b": [2]
}
Run Code Online (Sandbox Code Playgroud)

我知道如何在 for 循环中执行此操作,我可以只使用一行来完成这项工作吗?

Roa*_*ner 5

一个简单的方法是使用一个简单collections.defaultdict()的列表:

from collections import defaultdict

lst = [("a", 1), ("b", 2), ("a", 3)]

items = defaultdict(list)
for k, v in lst:
    items[k].append(v)

print(items)
Run Code Online (Sandbox Code Playgroud)

这创造了:

defaultdict(<class 'list'>, {'a': [1, 3], 'b': [2]})
Run Code Online (Sandbox Code Playgroud)

Note: If you want the final result to be a normal dictionary, you can just wrap dict().

If you really want a one liner, you could use itertools.groupby() in a dict comprehension:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> lst = [("a", 1), ("b", 2), ("a", 3)]
>>> {k: list(map(itemgetter(1), g)) for k, g in groupby(sorted(lst, key=itemgetter(0)), key=itemgetter(0))}
{'a': [1, 3], 'b': [2]}
Run Code Online (Sandbox Code Playgroud)

Which can also be written more cleanly as:

{k: [x[1] for x in g] for k, g in groupby(sorted(lst, key=itemgetter(0)), key=itemgetter(0))}
Run Code Online (Sandbox Code Playgroud)

The above solution has O(NlogN) complexity due to sorting, a requirement if you want to group similar items together. This is less efficient than The first defaultdict solution, which is O(N), since you only need to iterate the list once. The first solution would be more preferable, since its easier to read, efficient and maintainable.