如何按嵌入在其中的时间和日期对字符串列表进行排序?

时间:2018-11-22 03:29:32

标签: python sorting

列出项目:

'Cam218-10-03_16_05-21-54.jpg',
'Cam318-10-03_17_04-21-54.jpg',
'Cam418-10-03_16_04-21-54.jpg',
'Cam218-10-02_16_05-21-54.jpg',
'Cam318-10-02_17_04-21-54.jpg',
'Cam418-10-02_16_04-21-54.jpg',
'Cam218-10-02_16_04-08-31.jpg',
'Cam318-10-02_16_04-08-30.jpg',
'Cam418-10-02_16_04-08-30.jpg',
'Cam518-10-02_16_04-08-35.jpg',
'Cam618-10-02_16_04-08-36.jpg',
'Cam118-10-02_16_04-08-36.jpg',
'Cam118-10-03_16_05-21-54.jpg',
'Cam218-10-03_16_05-21-54.jpg',
'Cam118-10-03_16_05-21-54.jpg',
'Cam118-10-03_16_04-08-31.jpg',

使用python,如何使用时间戳对其进行排序?我希望输出为:

'Cam118-10-03_16_04-08-31.jpg',
'Cam218-10-02_16_04-08-31.jpg',
'Cam318-10-02_16_04-08-30.jpg',
'Cam418-10-02_16_04-08-30.jpg',
'Cam518-10-02_16_04-08-35.jpg',
'Cam618-10-02_16_04-08-36.jpg',

我已经尝试过了:

file=open("ram.txt","r")
data=file.readlines()
data.sort()
for i in data:
    print(i,end='')

1 个答案:

答案 0 :(得分:0)

file=open("ram.txt","r")
data=file.readlines() #assuming data now has the images in a list
dates = []
for img in data:
    img = img.split('-')[1] #remove the cam118 etc and just get date strings
    dates.append(img)
zipped_pairs = zip(dates, data) #zip them together 
sorted_dates = [x for _, x in sorted(zipped_pairs, reverse=True)]