(你已经改变了你的问题想用字符串,而不是与对象做到这一点,所以这个例子是字符串。)
使用每个字符串的索引列表谓词提供key
依据其进行排序您定列表:
>>> wanted_order = ['BODY.H', 'BODY.M', 'BODY.VL', 'WHL0.H']
>>> got_list = ['WHL0.H', 'BODY.H', 'BODY.VL', 'BODY.VL', 'WHL0.H', 'BODY.M']
>>> sorted(got_list, key=lambda s: wanted_order.index)
['BODY.H', 'BODY.M', 'BODY.VL', 'BODY.VL', 'WHL0.H', 'WHL0.H']
请注意,我在got_list
添加了一些额外的重复项目,以显示它如何会使用通用输入和多个每个。
顺便说一句,如果总是只有这4个对象,为什么不用这4个创建一个列表呢?
另外,如果从谓词中缺少一个字符串,则会出现错误。所以也许把它放在一个函数(而不是lambda)中,如果发生错误,并且返回另一个值。
编辑:
对于你愿意,你可以使用s.name
密钥和谓语什么对象版本(当然,wanted_order
有对象的名称):
>>> sorted(got_list, key=lambda s: wanted_order.index(s.name))
编辑2:
要处理got_list
中没有“姓名”的项目wanted_order
:
>>> def predicated_key(item):
... wanted_order = ['BODY.H', 'BODY.M', 'BODY.VL', 'WHL0.H']
... # put wanted_order in global scope if you prefer instead of here
... try:
... return wanted_order.index(item) # or item.name in your case
... except ValueError:
... return len(wanted_order) # since this will be higher than the
... # index of the any item on the list
...
>>> got_list = ['WHL0.H', 'BODY.H', 'something', 'BODY.VL',
... 'something else', 'BODY.VL', 'WHL0.H', 'BODY.M']
>>> sorted(got_list, key=predicated_key)
['BODY.H', 'BODY.M', 'BODY.VL', 'BODY.VL', 'WHL0.H', 'WHL0.H', 'something', 'something else']
这是没有足够的信息,它可能是很好的包括您使用的代码与实际结果和所需的行为。另请参见[如何创建最小,完整和可验证的示例](http://stackoverflow.com/help/mcve) –
问题是我不知道从哪里开始。 – aaro4130
没有人能够帮助你,除非你更清楚地解释你的问题... –