按给定的索引顺序对列表进行排序 [英] Sort list by given order of indices
问题描述
我有一个从文件中读取的行的列表.我需要按时间戳对列表进行排序.我已经使用正则表达式解析了时间戳,并将其放置在单独的列表中.这两个列表的索引将匹配.对时间戳列表进行排序后,便可以获取索引的顺序.
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)
这篇关于按给定的索引顺序对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!