1 回答
TA贡献1982条经验 获得超2个赞
如果你想对与每个水果相关的排序list,你可以执行以下操作:
>>> mydict = {k : sorted(v, key=lambda x : int(x[0])) for k, v in mydict.items()}
>>> mydict
{'orange': [['1', '00:00:03,950'],
['9', '00:00:24,030'],
['11', '00:00:29,640']],
'cherry': [['20', '00:00:54,449']],
'apple': [['14', '00:00:38,629']],
'banana': [['2', '00:00:06,840'],
['3', '00:00:09,180'],
['4', '00:00:10,830']]}
这是迭代字典的键值对,并按每个值的int第一个元素对每个值的元素进行排序。
但要明确的是,从 Python 3.7 开始,法线dict是有序的。所以在这里,您会看到水果名称的出现顺序与它们创建时的顺序相同 - 在早期的 Python 中,情况并非如此。
您还说您想要对键(水果名称)进行排序,但看起来您想要对值(行号和时间戳)进行排序。如果您想对水果名称进行额外排序,您可以拨打sorted电话来获取项目:
>>> mydict = {k : sorted(v, key=lambda x : int(x[0])) for k, v in sorted(mydict.items())}
>>> mydict
{'apple': [['14', '00:00:38,629']],
'banana': [['2', '00:00:06,840'],
['3', '00:00:09,180'],
['4', '00:00:10,830']],
'cherry': [['20', '00:00:54,449']],
'orange': [['1', '00:00:03,950'],
['9', '00:00:24,030'],
['11', '00:00:29,640']]}
# now mydict's keys are in alphabetical order, and its values are also ordered by line number
添加回答
举报