Python:列表dict的排序表示,在删除重复项后,按列表中元素的数量排序
我有一本这样的字典:Python:列表dict的排序表示,在删除重复项后,按列表中元素的数量排序,python,sorting,dictionary,Python,Sorting,Dictionary,我有一本这样的字典: example_dict = { 0: [(1,2),(3,4),(3,4),(4,5)], 1: [(1,2),(3,4),(5,6),(7,8)], 2: [(4,5),(7,8)]} 我希望在“临时”删除重复项后,通过每个列表中的元素数获得此词典的排序表示形式(仅用于排序,我不想删除元组)。因此,排序后的示例dict将具有以下键的(升序)顺序:2,0,1 有没有什么有效的,像蟒蛇一样的方法 print sorted(e
example_dict = {
0: [(1,2),(3,4),(3,4),(4,5)],
1: [(1,2),(3,4),(5,6),(7,8)],
2: [(4,5),(7,8)]}
我希望在“临时”删除重复项后,通过每个列表中的元素数获得此词典的排序表示形式(仅用于排序,我不想删除元组)。因此,排序后的示例dict
将具有以下键的(升序)顺序:2,0,1
有没有什么有效的,像蟒蛇一样的方法
print sorted(example_dict,key=lambda x: len(set(example_dict[x])))
输出:
[2, 0, 1]
[(2, [(4, 5), (7, 8)]), (0, [(1, 2), (3, 4), (3, 4), (4, 5)]), (1, [(1, 2), (3, 4), (5, 6), (7, 8)])]
或者,如果希望将字典项排序为元组列表:
print sorted(example_dict.items(),key=lambda x: len(set(x[1])))
输出:
[2, 0, 1]
[(2, [(4, 5), (7, 8)]), (0, [(1, 2), (3, 4), (3, 4), (4, 5)]), (1, [(1, 2), (3, 4), (5, 6), (7, 8)])]
输出:
[2, 0, 1]
[(2, [(4, 5), (7, 8)]), (0, [(1, 2), (3, 4), (3, 4), (4, 5)]), (1, [(1, 2), (3, 4), (5, 6), (7, 8)])]
或者,如果希望将字典项排序为元组列表:
print sorted(example_dict.items(),key=lambda x: len(set(x[1])))
输出:
[2, 0, 1]
[(2, [(4, 5), (7, 8)]), (0, [(1, 2), (3, 4), (3, 4), (4, 5)]), (1, [(1, 2), (3, 4), (5, 6), (7, 8)])]
最适合您的数据结构可能是。然后,您可以按排序顺序遍历字典
In [1]: from collections import OrderedDict
In [2]: example_dict_sorted = OrderedDict(sorted(example_dict.items(), key=lambda tup: len(set(tup[1]))))
In [3]: example_dict_sorted[0]
Out[3]: [(1, 2), (3, 4), (3, 4), (4, 5)]
In [4]: example_dict_sorted[1]
Out[4]: [(1, 2), (3, 4), (5, 6), (7, 8)]
In [5]: example_dict_sorted[2]
Out[5]: [(4, 5), (7, 8)]
In [6]: for key in example_dict_sorted:
...: print key
2
0
1
最适合您的数据结构可能是。然后,您可以按排序顺序遍历字典
In [1]: from collections import OrderedDict
In [2]: example_dict_sorted = OrderedDict(sorted(example_dict.items(), key=lambda tup: len(set(tup[1]))))
In [3]: example_dict_sorted[0]
Out[3]: [(1, 2), (3, 4), (3, 4), (4, 5)]
In [4]: example_dict_sorted[1]
Out[4]: [(1, 2), (3, 4), (5, 6), (7, 8)]
In [5]: example_dict_sorted[2]
Out[5]: [(4, 5), (7, 8)]
In [6]: for key in example_dict_sorted:
...: print key
2
0
1
Python字典天生就是无序的。你不能把它们分类。(尽管可以将它们的内容作为键值对进行排序表示。)没错,我已经编辑了我的问题。Python字典本质上是无序的。你不能把它们分类。(尽管可以将其内容排序为键值对。)没错,我已经编辑了我的问题。