python – 按组件排序字符串列表

长列表包含一些要排序的元素.

实际上每个元素有4个内容:名称,输入/输出,区域和日期&时间,由’〜’连接. (‘〜’可以更改.)我想将列表重组为排序顺序.

a_list = ["Chris~Check-in~Zoom A~11/13/2013 05:20",
"Chris~Check-in~Zoom G~11/15/2013 14:09",
"Frank E~Check-in~Zoom K~11/11/2013 08:48",
"Frank E~Check-in~Zoom K~11/15/2013 21:32",
"Kala Lu S~Check-in~Zoom N~11/13/2013 07:20",
"Milly Emily~Check-in~Zoom G~11/13/2013 01:08",
"Milly Emily~Check-in~Zoom E~11/16/2013 14:39",
"Milly Amy~Check-in~Zoom G~11/10/2013 20:14",
"Milly Amy~Check-in~Zoom A~11/16/2013 08:55",
"Milly Amy~Check-in~Zoom O~11/14/2013 21:57",
"Milly Amy~Check-in~Zoom A~11/15/2013 10:45",
"Nago Iko~Check-in~Zoom K~11/16/2013 20:42",
"Nago Iko~Check-in~Zoom K~11/14/2013 10:46",
"Liz D~Check-in~Zoom N~11/15/2013 01:46",
"Liz D~Check-in~Zoom A~11/12/2013 09:54",
"Liz D~Check-in~Zoom G~11/16/2013 13:15",
"Chris~Check-out~Zoom A~11/13/2013 13:42",
"Chris~Check-out~Zoom G~11/11/2013 14:21",
"Chris~Check-out~Zoom G~11/16/2013 09:41",
"Frank E~Check-out~Zoom K~11/14/2013 03:02",
"House P~Check-out~Zoom K~11/10/2013 11:17",
"Kala Lu S~Check-out~Zoom G~11/11/2013 23:27",
"Kala Lu S~Check-out~Zoom N~11/14/2013 11:17"]

它可以导入到MS Excel并进行排序,但我想知道Python是否可以完成这项工作.

是否可以按列表中的顺序对它们进行排序:1.名称,2.日期和时间3.区域4.进/出?喜欢:

new_list = ["Chris~Check-out~Zoom G~11/08/2014 14:21",
"Chris~Check-in~Zoom A~11/10/2014 05:20",
"Chris~Check-out~Zoom A~11/10/2014 13:42",
"Chris~Check-in~Zoom G~11/12/2014 14:09",
"Chris~Check-out~Zoom G~11/13/2014 09:41",
"Frank E~Check-in~Zoom K~11/08/2014 08:48",
"Frank E~Check-out~Zoom K~11/11/2014 03:02",
"Frank E~Check-in~Zoom K~11/12/2014 21:32",
...
...]

谢谢.

最佳答案 您可以拆分列表,然后使用自定义键功能进行排序.但是您需要首先解析日期以正确排序它们.

import datetime

new_l = sorted((x.split('~') for x in l),
               key=lambda x: (x[0],
                              datetime.datetime.strptime(x[3], '%m/%d/%Y %H:%M'),
                              x[2],
                              x[1]))

键函数返回一个元组.元组按字典顺序进行比较;比较第一项;如果它们相同则比较第二项,依此类推

或者,您可以分阶段进行分类.这将允许您指定要按升序或降序排序的列.

from operator import itemgetter

nl = [x.split('~') for x in l]

nl.sort(key=itemgetter(1))
nl.sort(key=itemgetter(2))
nl.sort(key=lambda x: datetime.datetime.strptime(x[3], '%m/%d/%Y %H:%M'),
        reverse=True) # Newest first
nl.sort(key=itemgetter(0))

请记住,两种方式都会使新列表分割如下:

new_list = [["Chris", "Check-out", "Zoom G", "11/08/2014 14:21"], ...]

如果要将它们更改回原始表单,可以加入它们:

new_list_joined = ['~'.join(x) for x in new_list]
点赞