English 中文(简体)
字典中任意排列的字典清单
原标题:reordering list of dicts arbitrarily in python
  • 时间:2010-07-21 16:11:53
  •  标签:
  • python
  • list

我有四条dict(途径4)清单,其中列举这样的内容:

[{ id : 1 , name : alfa },{ id : 2 , name : bravo },{ id : 3 , name : charlie },{ id : 4 , name : delta }]

我完全知道我想他们的话,那就是:

2, 3, 1, 4

重新排列顺序的最简单方式是什么?

最佳回答

如果它总是四人,而且你总是知道这一命令,那么就好像:

lst = [{...},{...},{...},{...}]
ordered = [lst[1],lst[2],lst[0],lst[3]]

如果你打算id,就应该:

ordered = sorted(lst, key=lambda d: [2,3,1,4].index(int(d[ id ])))

请注意,index(>>>>,但tt 要求您建立字典。 因此,对于小型投入来说,这实际上可能更快。 在你的情况下,有4个要素,有10个比较得到了保证。 使用<条码>日,这一氮比 to基解决办法高10%,但确实如此,因为两者都不大可能重要。

问题回答

这里具有强行下达通缉令的一般功能(任何重要价值,如不列入通缉令,则在定案清单的末尾处,任意分列):

def ordered(somelist, wantedorder, keyfunction):
    orderdict = dict((y, x) for x, y in enumerate(wantedorder))
    later = len(orderdict)
    def key(item):
        return orderdict.get(keyfunction(item), later)
    return sorted(somelist, key=key)

页: 1

import operator
sortedlist = ordered(dictlist, ( 2 ,  3 ,  1 ,  4 ),
                     operator.itemgetter( id ))

非普遍解决办法:

lst = [{ id : 1 , name : alfa },{ id : 2 , name : bravo },{ id : 3 , name : charlie },{ id : 4 , name : delta }]
order = ["2", "3", "1", "4"]
indexes = dict((idfield, index) for (index, idfield) in enumerate(order))
print sorted(lst, key=lambda d: indexes[d["id"]])
# [{ id :  2 ,  name :  bravo }, { id :  3 ,  name :  charlie }, { id :  1 ,  name :  alfa }, { id :  4 ,  name :  delta }]

这里概述:

def my_ordered(it, wanted_order, key):
    indexes = dict((value, index) for (index, value) in enumerate(wanted_order))
    return sorted(it, key=lambda x: indexes[key(x)])

import operator  
print my_ordered(lst, order, operator.itemgetter("id"))
the_list.sort(key=lambda x: (3, 1, 2, 4)[int(x["id"])-1])

Update0

更简单的新答案

the_list = [the_list[i - 1] for i in (2, 3, 1, 4)]

这样,欧佩组织就可以看到他所期望的秩序,而这里并不需要这种分类。 这很可能也很快。

如果你想在不考虑法令内容的情况下重新排列顺序:

>>> order = 2, 3, 1, 4
>>> d = [{ id : 1 , name : alfa },{ id : 2 , name : bravo },{ id : 3 , name : charlie },{ id : 4 , name : delta }]
>>> index = dict(enumerate(dd))
>>> [index[i-1] for i in order]
[{ id :  2 ,  name :  bravo }, { id :  3 ,  name :  charlie }, { id :  1 ,  name :  alfa }, { id :  4 ,  name :  delta }]

如果你想把标题按以下顺序排列:

>>> sorted(d, key=lambda x: order.index(int(x[ id ])))
[{ id :  2 ,  name :  bravo }, { id :  3 ,  name :  charlie }, { id :  1 ,  name :  alfa }, { id :  4 ,  name :  delta }]




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签