[英]Sorting lists in dictionary
Could someone please explain how I could sort a list in dictionary? 有人可以解释一下如何在字典中对列表进行排序吗? For example: 例如:
B = {'Mary': [(850, 1000), (9, 10), (1000, 3000), (250, 550)], 'john': [(500, 1000), (800,3000), (20, 100), (5, 36)]}
Using the 'sorted' function, how do I sort it in ascending order based on the first value in the list? 使用“排序”功能,如何基于列表中的第一个值以升序对其进行排序? Likewise, how do I sort it in ascending order based on the second value in the list? 同样,如何根据列表中的第二个值将其升序排序?
Many thanks 非常感谢
I would iterate through your items, then in-place sort
based on the first element of each tuple
. 我将遍历您的项目,然后根据每个tuple
的第一个元素进行就地sort
。
B = {
'Mary': [(850, 1000), (9, 10), (1000, 3000), (250, 550)],
'john': [(500, 1000), (800,3000), (20, 100), (5, 36)],
}
for item in B:
B[item].sort(key = lambda i: i[0])
Output 输出量
{
'john': [(5, 36), (20, 100), (500, 1000), (800, 3000)],
'Mary': [(9, 10), (250, 550), (850, 1000), (1000, 3000)]
}
You have to use its key argument. 您必须使用其key参数。 Key is a function which takes the element of the iterable as an agrument and returns the value on which sorting is based: 键是一个函数,它将iterable的元素作为汇总,并返回基于排序的值:
for e in B:
B[e] = sorted(B[e], key=lambda x: x[Element_ID])
Element ID is the index of the element on which you want to base your sort. 元素ID是要作为排序依据的元素的索引。 So it will be 1 if you want to sort according to the second element and 0 if you want to sort according to the first element. 因此,如果要根据第二个元素排序,则为1;如果要根据第一个元素排序,则为0。
EDIT: 编辑:
Also it would be faster to use list's sort method instead of sorted: 同样,使用列表的sort方法而不是sorted会更快:
for e in B:
B[e].sort(B[e], key=lambda x: x[Element_ID])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.