[英]python: flat list of dict values
I have a list
of dicts
like so: 我有一个像这样的dicts
list
:
a = [ {'list':[1,2,3]}, {'list':[1,4,5]} ]
Am trying to get a flat set of the values in the list
key like {1,2,3,4,5}
. 我试图在list
键中获得一组平面值,如{1,2,3,4,5}
。 What's the quickest way? 什么是最快的方式?
You can write a loop like: 你可以编写一个循环:
result = set()
for row in a:
result.update(row['list'])
which I think will work reasonably fast. 我认为它会合理地运作。
Or you can simply use set comprehension and that will result in the following one-liner : 或者您可以简单地使用集合理解 ,这将导致以下单行 :
result = {x for row in a for x in row['list']}
In case not all elements contain a 'list'
key, you can use .get(..)
with an empty tuple (this will reduce construction time): 如果并非所有元素都包含'list'
键,则可以将.get(..)
与空元组一起使用(这将减少构建时间):
result = {x for row in a for x in row.get('list',())}
It is not clear what your definition of "quickest" is, but whether it is speed or number of lines I would use a combination of itertools and a generator. 目前尚不清楚你对“最快”的定义是什么,但无论是速度还是行数我都会使用itertools和一个生成器的组合。
>>> import itertools
>>> a = [ {'list':[1,2,3]}, {'list':[1,4,5]} ]
>>> b = set(itertools.chain.from_iterable(x['list'] for x in a if 'list' in x))
Note that I have added a guard against any elements that may not contain a 'list'
key; 请注意,我添加了一个警告,防止任何可能不包含'list'
键的元素; you can omit that if you know this will always be true. 你可以省略,如果你知道这将永远是真的。
reduce
easily. 可以通过reduce
平面列表。 All you need to use initializer - third argument in the reduce
function. 您只需要使用初始化程序 - reduce
函数中的第三个参数。
reduce(
lambda _set, _dict, key='list': _set.update(
_dict.get(key) or set()) or _set,
a,
set())
Above code works for both python2 and python3, but you need to import reduce module as from functools import reduce
. 上面的代码适用于python2和python3,但是你需要from functools import reduce
导入reduce模块。 Refer below link for details. 请参阅以下链接了解详情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.