Sort list by given order of indices

前端 未结 4 1321
天涯浪人
天涯浪人 2021-02-19 07:40

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. T

相关标签:
4条回答
  • 2021-02-19 08:30
    sorted(zip(listofTimes, listofLines))
    
    0 讨论(0)
  • 2021-02-19 08:42

    I think you could do

    [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
    

    you could also do

    listofLines.sort(key=extract_time)
    

    or if you want to keep the original list intact,

    sorted(listofLines, key=extract_time)
    
    0 讨论(0)
  • 2021-02-19 08:46

    If you want to sort the original list because you, say, hald references to it elsewhere, you can assign to it the sorted list:

    my_list[:] = [my_list[i] for i in sorted_indexes]  # [:] is key!
    
    0 讨论(0)
  • 2021-02-19 08:47
    [listofLines[i] for i in sortedIndex]
    
    0 讨论(0)
提交回复
热议问题