根据时间值对字典中的元组进行排序 [英] sort tuples in dictionary based on time value

查看:120
本文介绍了根据时间值对字典中的元组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本这样的字典:

dict1 = {'key1': ['x1', [(time1,value1), (time3,value3), (time2,value2)]],
         'key2': ['x2', [(time6,value6), (time4,value4), (time5,value5)]],
          ...}

对于字典中的每个键,我希望根据时间对元组进行排序.看上面的例子,假设

For each key in the dictionary, I wish to sort the tuples based on the time. Looking at the example above, assume that

time1 < time2 < time3
time4 < time5 < time6

那么我希望的输出是

dict1 = {'key1': ['x1', [(time1,value1), (time2,value2), (time3,value3)]],
         'key2': ['x2', [(time4,value4), (time5,value5), (time6,value6)]],
          ...}

每个键"x1","x2" ..等的第一个值都是多余的,应该删除(如果有的话).

The first value for each key 'x1', 'x2' .. etc are redundant and should (if anything) just be removed.

有人可以帮助我解决基于时间值对字典中的元组进行排序的问题吗?

Can anyone help me with the issue of sorting the tuples in the dictionary based on the time value?

非常感谢.

推荐答案

您可以对sorted使用dict理解:

You can just use a dict comprehension with sorted:

>>> {k: [v[0]] + [sorted(v[1])] for k, v in dict1.items()}
{'key1': ['x1', [('time1', 'value1'), ('time2', 'value2'), ('time3', 'value3')]],
 'key2': ['x2', [('time4', 'value4'), ('time5', 'value5'), ('time6', 'value6')]]}

如果要删除x值,可以将此简化为:

If you want to drop the x value, you can simplify this to this:

>>> {k: sorted(v[1]) for k, v in dict1.items()}
{'key1': [('time1', 'value1'), ('time2', 'value2'), ('time3', 'value3')],
 'key2': [('time4', 'value4'), ('time5', 'value5'), ('time6', 'value6')]}

我在这里使用字符串而不是实际的时间和值,但前提是这些时间对象可以正确比较,所以代码也可以一样.使用sorted,将仅按这些元组中的第一个元素对元组列表进行排序(如果第一个相等,则按第二个元素进行排序,依此类推).

I'm using strings instead of actual times and values here, but provided that those time objects compare properly, the code will work the same. Using sorted, the list of tuples will just be sorted by the first elements in those tuples (or the second in case the firsts are equal, etc).

这篇关于根据时间值对字典中的元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆