按给定的索引顺序对列表进行排序

编程入门 行业动态 更新时间:2024-10-10 17:26:22
本文介绍了按给定的索引顺序对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个从文件中读取的行的列表.我需要按时间戳对列表进行排序.我已经使用正则表达式解析了时间戳,并将其放置在单独的列表中.这两个列表的索引将匹配.对时间戳列表进行排序后,便可以获取索引的顺序.

I have a list of lines read from a file. I need to sort the list by time stamp. I have parsed out the time stamp using regular expressions and place them into a separate list. The indices of the two lists will match. Once I sort the list of time stamps, I can get the order of indices.

是否可以将相同顺序的索引应用于原始行列表?结果应该是原始行的排序列表.

Is there a way to apply the same order of indices to the original list of lines? The result should be the sorted list of original lines.

示例:

listofLines = ['log opened 16-Feb-2010 06:37:56 UTC', '06:37:58 Custom parameters are in use', 'log closed 16-Feb-2010 05:26:47 UTC'] listofTimes = ['06:37:56', '06:37:58', '05:26:47'] sortedIndex = [2,0,1]

推荐答案

我认为您可以做到

[line for (time,line) in sorted(zip(listofTimes, listofLines))]

但是,如果您具有(或可以编写)自动从行中提取时间的功能,

But if you have (or could write) a function to automatically extract the time from the line,

def extract_time(line): ... return time

您也可以

listofLines.sort(key=extract_time)

或者如果您想保持原始列表不变,

or if you want to keep the original list intact,

sorted(listofLines, key=extract_time)

更多推荐

按给定的索引顺序对列表进行排序

本文发布于:2023-11-29 08:56:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645932.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:顺序   索引   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!