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

python – 按组件排序字符串列表,第1张

概述长列表包含一些要排序的元素. 实际上每个元素有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/ 长列表包含一些要排序的元素.

实际上每个元素有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 datetimenew_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 itemgetternl = [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],reverse=True) # Newest firstnl.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]
总结

以上是内存溢出为你收集整理的python – 按组件排序字符串列表全部内容,希望文章能够帮你解决python – 按组件排序字符串列表所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1193237.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存