我是 Python 的新手(学习了几周),在理解数据结构方面遇到了一些麻烦。到目前为止,我所做的是从 .txt 文件中逐行提取文本,并将它们存储到字典中,例如,键为 animal。
database = {
'dog': ['apple', 'dog', '2012-06-12-08-12-59'],
'cat': [
['orange', 'cat', '2012-06-11-18-33-12'],
['blue', 'cat', '2012-06-13-03-23-48']
],
'frog': ['kiwi', 'frog', '2012-06-12-17-12-44'],
'cow': [
['pear', 'ant', '2012-06-12-14-02-30'],
['plum', 'cow', '2012-06-12-23-27-14']
]
}
# year-month-day-hour-min-sec
这样,当我打印我的字典时,它会按动物类型打印出来,并首先打印最新的日期。
按时间对这些数据进行排序的最佳方法是什么?我在 python 2.7 上。我的想法是
对于每个键:
获取列表(或列表列表)--> 获取第 3 个条目 --> '-'.split
它,--> 然后尝试 sorted(parameters)
我只是不太确定该怎么做...
最佳答案
遍历字典中的元素。对于每个值,在您的列表列表上运行 sorted
,并告诉排序算法使用列表的第三个字段作为“关键”元素。此关键元素用于将值与列表中的其他元素进行比较以确定排序顺序。要告诉 sorted
用列表中的哪个元素排序,请使用 operator.itemgetter
指定第三个元素。
由于您的时间戳具有严格的结构,并且时间戳中的每个字符在时间上都比下一个字符更重要,因此您可以自然地对它们进行排序,就像字符串一样 - 您不需要将它们转换为时间。
# Dictionary stored in d
from operator import itemgetter
# Iterate over the elements of the dictionary; below, by
# calling items(), k gets the key value of an entry and
# v gets the value of that entry
for k,v in d.items():
if v and isinstance(v[0], list):
v.sort(key=itemgetter(2)) # Start with 0, so third element is 2
关于python - 根据时间对字典列表值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11111071/