【问题标题】:python sort list of tuples on custom sortpython对自定义排序的元组列表进行排序
【发布时间】:2013-10-10 22:03:22
【问题描述】:

我正在尝试使用自定义预定义列表作为所需顺序,对元组的第一个元素上的元组列表进行排序。 所以我有这个列表

my_list=(['chr1',12],['chrX',32],['chr2',1],['chr1',79],['chr2',6])

第一个元素上的预定义列表是

custom_list=['chr1','chr2','chrX']

我希望输出是

(['chr1',12],['chr1',79],['chr2',1],['chr2',6],['chrX',32])

(目前,不需要对第二个元素进行排序。) 我不知道该怎么做。有人可以帮忙吗?

【问题讨论】:

  • 你有一个列表元组,而不是一个元组列表。

标签: python list sorting tuples


【解决方案1】:

您可以使用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]]

【讨论】:

  • 非常感谢。如果我有一个对象列表而不是元组列表,情况如何?我想对 custom_list 数组中该对象中的字段进行排序?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2017-03-23
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多