更新时间:2023-01-16 21:25:20
You can do the following, using itertools.chain
:
>>> from itertools import chain
# timeit: ~3.40
>>> [dict(chain(*map(dict.items, d.values()))) for d in data]
[{'l': 'Apple',
'b': 'Milk',
'd': 'Meatball',
'favourite': 'coke',
'dislike': 'juice'},
{'l': 'Apple1',
'b': 'Milk1',
'dislike': 'juice3',
'favourite': 'coke2',
'd': 'Meatball2'}]
chain
,map
,*
的用法使该表达式成为以下双重嵌套理解的简写,它实际上在我的系统上表现更好(Python 3.5.2),并且不再那么长:
The usage of chain
, map
, *
make this expression a shorthand for the following doubly nested comprehension which actually performs better on my system (Python 3.5.2) and isn't that much longer:
# timeit: ~2.04
[{k: v for x in d.values() for k, v in x.items()} for d in data]
# Or, not using items, but lookup by key
# timeit: ~1.67
[{k: x[k] for x in d.values() for k in x} for d in data]
RoadRunner的循环和更新方法在timeit: ~1.37
RoadRunner's loop-and-update approach outperforms both these one-liners at timeit: ~1.37