简体   繁体   English

如何基于字典中的元素创建列表?

[英]How to create list based on elements from dictionary?

I have this list of dictionaries: 我有以下词典列表:

L = [{'code': 'UE', 'country': 'France'}, {'code': 'AM', 'country': 'canada'}, {'code': 'AF', 'country': 'morocco'}]

Is there any way to retrieve a list of codes sorted like this: codes = ['AF', 'AM', 'UE'] ? 是否有任何方法可以检索按以下方式排序的代码列表: codes = ['AF', 'AM', 'UE']

You can pass a generator to sorted : 您可以将生成器传递给sorted

>>> codes = sorted( d['code'] for d in L )
>>> codes
['AF', 'AM', 'UE']

Another option is to pass a list comprehension to sorted , which @MartijnPieters showed to be faster in this case. 另一个选择是将列表理解传递给sorted ,@MartijnPieters在这种情况下显示出更快。

codes = sorted([ d['code'] for d in L ])

Use a list comprehension selecting the key you need, passing the values to the sorted() function : 使用列表理解选择所需的键,然后将值传递给sorted()函数

codes = sorted([d['code'] for d in L])

Demo: 演示:

>>> L = [{'code': 'UE', 'country': 'France'}, {'code': 'AM', 'country': 'canada'}, {'code': 'AF', 'country': 'morocco'}]
>>> sorted([d['code'] for d in L])
['AF', 'AM', 'UE']

Here, a list comprehension is faster than a generator expression: 在这里,列表理解比生成器表达式快:

>>> from timeit import timeit
>>> timeit("sorted(d['code'] for d in L)", 'from __main__ import L')
2.1713640689849854
>>> timeit("sorted([d['code'] for d in L])", 'from __main__ import L')
0.9132740497589111

sorted() requires a list to sort, so either you give it a list or it'll build a list from the iterable. sorted()需要一个列表进行排序,因此您可以给它一个列表,也可以从iterable中构建一个列表。 Building a list from a generator expression is (a lot) less efficient than giving it a list in the first place. 从生成器表达式构建列表比(首先)为其提供列表的效率低很多。

Use sorted() function with list comprehension: sorted()函数与列表理解一起使用:

>>> L = [{'code': 'UE', 'country': 'France'}, {'code': 'AM', 'country': 'canada'}, {'code': 'AF', 'country': 'morocco'}]
>>>
>>> sorted([d['code'] for d in L])
['AF', 'AM', 'UE']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM