可以使用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]]
你有没有列表的元组,而不是一个元组列表。 – arshajii