此问题在此处已有答案:
(19个答案)2小时前关门了。我有一个列表,当我循环遍历数据时,我会向它追加一个字典......并且我希望按字典键之一排序。例如:
data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict)
我想按“date”的值对列表进行逆序排序
zzlelutf1#
您可以这样做:
list.sort(key=lambda item:item['date'], reverse=True)
chhqkbe12#
from operator import itemgetter your_list.sort(key=itemgetter('date'), reverse=True)
list
dict
tuple
collections.namedtuple
from collections import namedtuple from operator import itemgetter Row = namedtuple('Row', 'title date') rows = [Row(row.title, row.created_on) for row in data] rows.sort(key=itemgetter(1), reverse=True)
示例:
>>> lst = [Row('a', 1), Row('b', 2)] >>> lst.sort(key=itemgetter(1), reverse=True) >>> lst [Row(title='b', date=2), Row(title='a', date=1)]
或者
>>> from operator import attrgetter >>> lst = [Row('a', 1), Row('b', 2)] >>> lst.sort(key=attrgetter('date'), reverse=True) >>> lst [Row(title='b', date=2), Row(title='a', date=1)]
以下是namedtuple的内部外观:
namedtuple
>>> Row = namedtuple('Row', 'title date', verbose=True) class Row(tuple): 'Row(title, date)' __slots__ = () _fields = ('title', 'date') def __new__(cls, title, date): return tuple.__new__(cls, (title, date)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Row object from a sequence or iterable' result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result def __repr__(self): return 'Row(title=%r, date=%r)' % self def _asdict(t): 'Return a new dict which maps field names to their values' return {'title': t[0], 'date': t[1]} def _replace(self, **kwds): 'Return a new Row object replacing specified fields with new values' result = self._make(map(kwds.pop, ('title', 'date'), self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result def __getnewargs__(self): return tuple(self) title = property(itemgetter(0)) date = property(itemgetter(1))
p5fdfcr13#
你可以这样做:
from operator import itemgetter list.sort(key=itemgetter('date'), reverse=True)
另请参阅:How do I sort a list of dictionaries by a value of the dictionary?
rsl1atfo4#
直接对数据(或数据副本)进行排序,然后构建字典列表。使用带有适当键函数(可能是operator.attrgetter)的函数进行排序
idv4meu85#
如果你喜欢简洁:
data = "data from database" sorted_data = sorted( [{'title': x.title, 'date': x.created_on} for x in data], key=operator.itemgetter('date'), reverse=True)
5条答案
按热度按时间zzlelutf1#
您可以这样做:
chhqkbe12#
相关注解
list
,dict
作为变量名,它们是Python内置的变量名,这会让你的代码难以阅读。tuple
或collections.namedtuple
或自定义的类似结构的类示例:
或者
以下是
namedtuple
的内部外观:p5fdfcr13#
你可以这样做:
另请参阅:How do I sort a list of dictionaries by a value of the dictionary?
rsl1atfo4#
直接对数据(或数据副本)进行排序,然后构建字典列表。使用带有适当键函数(可能是operator.attrgetter)的函数进行排序
idv4meu85#
如果你喜欢简洁: