您可以使用该list.index()
函数将位置custom_list
转换为排序键:
sorted(my_list, key=lambda x: (custom_list.index(x[0]), x[1]))
但是,您可能希望将您的custom_list
变成字典,以便更快地映射:
custom_list_indices = {v: i for i, v in enumerate(custom_list)}
sorted(my_list, key=lambda x: (custom_list_indices.get(x[0]), x[1]))
字典查找需要恒定的时间,list.index()
时间与列表的长度成正比。
另一个优点是,使用字典,您可以为字典中未找到的条目返回默认值(None
在此示例中);list.index()
将引发ValueError
异常。
演示:
>>> my_list=(['chr1',12],['chrX',32],['chr2',1],['chr1',79],['chr2',6])
>>> custom_list=['chr1','chr2','chrX']
>>> sorted(my_list, key=lambda x: (custom_list.index(x[0]), x[1]))
[['chr1', 12], ['chr1', 79], ['chr2', 1], ['chr2', 6], ['chrX', 32]]
>>> custom_list_indices = {v: i for i, v in enumerate(custom_list)}
>>> sorted(my_list, key=lambda x: (custom_list_indices.get(x[0]), x[1]))
[['chr1', 12], ['chr1', 79], ['chr2', 1], ['chr2', 6], ['chrX', 32]]