自定义订单列表python

时间:2013-08-23 17:37:22

标签: python list

在此处扩展我的第一个问题:Custom sort order of list

mylist1 = ['moi.alpha', 'moi.red']
mylist2 = ['test.green', 'test.alpha','test.red']

我希望按此顺序对其进行排序:['red','green','blue','alpha']

这样: mylist1 = ['moi.red','moi.alpha']
mylist2 = ['test.red','test.green','test.alpha']

请注意,“moi”和“test”是动态的,具体取决于代码中分配的值...

2 个答案:

答案 0 :(得分:2)

这与上一个问题完全相同,在sort_order中查找索引时使用简单的拆分函数:

mylist1 = ['test.alpha', 'test.green']
mylist2 = ['asdf.blue', 'asdf.alpha', 'asdf.red']
sort_order = ['red', 'blue', 'green', 'alpha']
mylist2.sort(key=lambda x: sort_order.index(x.split(".")[1]))
mylist1.sort(key=lambda x: sort_order.index(x.split(".")[1]))
print mylist2
print mylist1

输出:

['asdf.red', 'asdf.blue', 'asdf.alpha']
['test.green', 'test.alpha']

你真正需要的是:

def sort_list(lst):
    sort_order = ['red', 'blue', 'green', 'alpha']
    lst.sort(key=lambda x: sort_order.index(x.split(".")[1]))
    return lst

答案 1 :(得分:1)

与上次类似,只需在执行查找之前提取所需的部分:

your_order = ['red','green','blue','alpha']
order = {v:i for i,v in enumerate(your_order)}
mylist2.sort(key=lambda L: order.get(L.partition('.')[2]))