python - 在 Python 中对关联数组进行排序

标签 python

<分区>

如何在 Python 中按键对关联数组进行排序?

我有以下结构:

people = [
    {'name' : 'Bob', 'number' : '123'},
    {'name' : 'Bill', 'number' : '234'},
    {'name' : 'Dave', 'number' : '567'},
]

我想按名字排序。是否有内置函数可以执行此操作?

最佳答案

使用sorted函数的key参数:

sorted(people, key=lambda dct: dct['name'])

有一个excellent Sorting HOWTO这解释了它是如何工作的。


>>> people = [
    {'name' : 'Bob', 'number' : '123'},
    {'name' : 'Bill', 'number' : '234'},
    {'name' : 'Dave', 'number' : '567'},
]       
>>> sorted(people, key=lambda dct: dct['name'])
[{'name': 'Bill', 'number': '234'}, 
 {'name': 'Bob', 'number': '123'}, 
 {'name': 'Dave', 'number': '567'}]

或者,你可以使用

import operator
sorted(people, key=operator.itemgetter('name'))

使用 operator.itemgetter('name') 比使用 lambda dct: dct['name'].

关于python - 在 Python 中对关联数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16743785/

相关文章:

python - 在 ipython 中出现异常时停止执行 Python 程序

python - 隐藏 scikit-learn ConvergenceWarning : "Increase the number of iterations (max_iter) or scale the data"

Python:索引子字符串中的位置

python - django.core.exceptions.ImproperlyConfigured : Could not resolve URL for hyperlinked relationship using view name "user-detail"

python - Python 中的 "all"函数是如何工作的?

python - Python 是否会在赋值时复制对象?

python - RegexpTokenizer 日语句子 - python

python - 在Python中从字符串中去除非字母字符的代码

Python/Pandas - 性能 - 计算列中值的出现百分比

python - 编译 Python