单词列表中的单个列表

时间:2013-01-26 15:22:27

标签: python list dictionary

这是Python中的列表:

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

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

像这样:

A 1 = [3,4,14,24]

我用for循环制作了这个,但还有另一种方法吗?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]

答案 2 :(得分: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词典是无序的。这意味着不保证每个字典中键(及其值)的排序。

答案 3 :(得分:0)

使用itertools chain method

import itertools

a = [{'a':3,'b':4}, {'c':14,'d':24}]
list(itertools.chain(*(x.itervalues() for x in a)))
>>> [3, 4, 14, 24]