2

这是 Python 中的列表:

a = [{a:3,b:4}, {c:14,d:24}]

如何创建仅包含字典值的列表?

像这样:

a1=[3,4,14,24]

我用for循环做了这个,但是还有其他方法吗?

4

4 回答 4

3

由于订单显然无关紧要:

>>> a = [{'a':3,'b':4}, {'c':14,'d':24}]
>>> a
[{'a': 3, 'b': 4}, {'c': 14, 'd': 24}]

您可以在 listcomp 中获取值:

>>> [d.values() for d in a]
[[3, 4], [14, 24]]

然后使用嵌套的 listcomp 将其展平:

>>> [value for d in a for value in d.values()]
[3, 4, 14, 24]

这相当于

>>> newlist = []
>>> for d in a:
...     for value in d.values():
...         newlist.append(value)
... 
>>> newlist
[3, 4, 14, 24]

如果你真的不想要那个词for,我想你可以使用

>>> from itertools import chain
>>> list(chain(*map(dict.values, a)))
[3, 4, 14, 24]

[更新:]

一些性能比较(主要是为了提供有关大 N 缩放的信息):

>>> a = [{'a':3,'b':4}, {'c':14,'d':24}]
>>> 
>>> timeit [value for d in a for value in d.itervalues()]
1000000 loops, best of 3: 1.02 us per loop
>>> timeit [value for d in a for value in d.values()]
1000000 loops, best of 3: 1.32 us per loop
>>> timeit list(chain(*map(dict.values, a)))
100000 loops, best of 3: 4.45 us per loop
>>> timeit reduce(operator.add, (d.values() for d in a))
100000 loops, best of 3: 2.01 us per loop
>>> timeit sum((d.values() for d in a), [])
100000 loops, best of 3: 2.08 us per loop
>>> 
>>> a = [{'a':3,'b':4}, {'c':14,'d':24}] * 1000
>>> 
>>> timeit [value for d in a for value in d.itervalues()]
1000 loops, best of 3: 612 us per loop
>>> timeit [value for d in a for value in d.values()]
1000 loops, best of 3: 915 us per loop
>>> timeit list(chain(*map(dict.values, a)))
1000 loops, best of 3: 1.07 ms per loop
>>> timeit reduce(operator.add, (d.values() for d in a))
100 loops, best of 3: 17.1 ms per loop
>>> timeit sum((d.values() for d in a), [])
100 loops, best of 3: 17.1 ms per loop
于 2013-01-26T15:44:38.997 回答
2

这可以使用列表推导在单行中完成:

>>> a = [{'a':3,'b':4}, {'c':14,'d':24}]    #List


>>> [v for d in a for v in d.values()] #Comprehension
    [3, 4, 14, 24]
于 2013-01-26T15:45:31.837 回答
1
In [9]: import operator

In [10]: a = [{'a':3,'b':4}, {'c':14,'d':24}]

In [11]: reduce(operator.add, (d.values() for d in a))
Out[11]: [3, 4, 14, 24]

请记住,Python 字典是无序的。这意味着不能保证每个字典中键(及其值)的顺序。

于 2013-01-26T15:44:19.837 回答
0

使用itertools chain 方法

import itertools

a = [{'a':3,'b':4}, {'c':14,'d':24}]
list(itertools.chain(*(x.itervalues() for x in a)))
>>> [3, 4, 14, 24]
于 2013-01-26T16:00:46.893 回答