Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 根据key,value对字典列表进行排序,使得key,value对中的前三个应该出现在给定的dict列表中_Python_List_Dictionary - Fatal编程技术网

Python 根据key,value对字典列表进行排序,使得key,value对中的前三个应该出现在给定的dict列表中

Python 根据key,value对字典列表进行排序,使得key,value对中的前三个应该出现在给定的dict列表中,python,list,dictionary,Python,List,Dictionary,如果排序大于该dict应首先出现的顺序,则按“排序”键对dict进行排序,然后包含下一个更大顺序的dict和前三个更大顺序的dict应存储在列表中 输入: my_list = [{u'item_group': u'Bits Special', u'item_name': u'Tool Bits-Metric', u'ordering': 1}, {u'item_group': u'Performance Drills 3X',

如果排序大于该dict应首先出现的顺序,则按“排序”键对dict进行排序,然后包含下一个更大顺序的dict和前三个更大顺序的dict应存储在列表中

输入:

my_list = [{u'item_group': u'Bits Special',
         u'item_name': u'Tool Bits-Metric',
         u'ordering': 1},
        {u'item_group': u'Performance Drills 3X',
         u'item_name': u'Drills-Short-Metric',
         u'ordering': 3},
        {u'item_group': u'Hand Taps',
         u'item_name': u'Shank-Metric',
         u'ordering': 4},
        {u'item_group': u'Tool Bits',
         u'item_name': u'T42-Square HSS Tool Bits-BSW',
         u'ordering': 2,}]
预期o/p:

     op_list = [{u'item_group': u'Hand Taps',u'item_name': u'Shank-Metric',
           u'ordering': 4},{u'item_group': u'Performance Drills 3X',
           u'item_name': u'Drills-Short-Metric',u'ordering': 3}, 
          {u'item_group': u'Tool Bits',u'item_name': u'T42-Square HSS 
           Tool Bits-BSW',u'ordering': 2,}]
我试过:

 for i in mylist:
       if i['ordering']>mylist['ordering']:
          op_list.append(i)

下面的示例演示了如何对列表进行排序,并给出了用于比较的键。你需要重新旋转(即下降),然后进入前三名

简化你所拥有的,考虑一下

my_list=[{u'ordering':1}, {u'ordering':3}, {u'ordering':4}, {u'ordering':2}]
您可以对其进行排序:

>>> sorted(my_list, key=lambda d: d[u'ordering'], reverse=True)
[{'ordering': 4}, {'ordering': 3}, {'ordering': 2}, {'ordering': 1}]
切掉你需要的东西:

>>> sorted(my_list, key=lambda d: d[u'ordering'], reverse=True)[:3]
[{'ordering': 4}, {'ordering': 3}, {'ordering': 2}]

我可以建议你再努力一点吗?如果您花时间阅读
list.sort()
的文档,这确实是一项简单的任务。