按python中条目名称中包含的时间戳对列表中的条目进行排序



我是编程新手,希望根据条目名称中包含的时间戳对列表allIetsDatalight中的条目进行排序。因此,我将我的path的所有文件(具有以下名称结构125_L_2020-11-12_12-08-35.IV2((以.IV2结尾(放在列表allIetsDatalight中,现在我想对所有条目进行排序。另一个问题是,文件名125_L_的前6个字符总是随文件的不同而变化。从第二天开始,我就一直在努力在互联网上找到一些东西,但我找不到适合我的程序的东西。

我的程序:

import os, sys
import matplotlib.pyplot as plt
import numpy as np
import math
path = 'C:\Users\simon'
allIetsDatalight = [f for f in os.listdir(path) if f.endswith('.IV2')]
for f in allIetsData:
if f == 'advIV.summary':
allIetsData.remove(f)
if f == 'darkIV.summary':
allIetsData.remove(f)
if f == 'lightIV.summary':
allIetsData.remove(f)
for iets in ietsToPlot:
Cellnumberlight, Celllight, Pixellight, Grouplight, Descriptionlight, Typelight, Illuminationdirectionlight, ScanDirectionlight, Voltagelight, Currentlight, Jlight, Timelight, PCElight =[],[],[],[],[],[],[],[],[],[],[],[],[]
f = open(path +"\" + allIetsDatalight[iets])
data = f.readlines()
i =0
for l in data:
x = l.split()  
if i == 3:
Pixellight.append(str(x[1])) 
Pixellight1 = str(Pixellight)[1:-1]
if i == 4:
Grouplight.append(str(x[1]))
Grouplight1 = str(Grouplight)[2:-2] 
if i == 5:
Descriptionlight.append(str(x[1]))
Descriptionlight1 = str(Descriptionlight)[1:-1]
if i == 8:
Typelight.append(str(x[1]))
Typelight1 = str(Typelight)[1:-1]
if i == 11:
ScanDirectionlight.append(str(x[1]))
ScanDirectionlight1 = str(ScanDirectionlight)[1:-1]
if i == 27:
PCElight.append(float(x[1]))
if i > 33:
Voltagelight.append(float(x[0]))
Jlight.append(float(x[2]))
i +=1 
for m in Grouplight1:
while int(m) > b:
plt.figure()
b +=1
print(Grouplight1)
plt.plot(Voltagelight, Jlight, linewidth=2, label= "Batchnr.: %s %s; Pixel: %s; direction: %s; lightsource: %s" % (Descriptionlight1.replace("'", ""), Grouplight1.replace("'", ""), Pixellight1.replace("'", ""), ScanDirectionlight1.replace("'", ""), Typelight1.replace("'", "")))
plt.title('JV-Measurement', fontsize=20)
plt.xlim(-0.5,1.25)
plt.legend()
plt.xlabel('Voltage in V ', fontsize=18)
plt.ylabel('J in mA/cm^2', fontsize=18)  
plt.show()

我想到了这个:

import re
from datetime import datetime
example = ["125_L_2021-11-12_12-08-35.IV2", "15_LA_2020-11-12_12-08-35.IV2", "1A25_%_2019-11-12_12-08-35.IV2"]
example.sort(key = lambda x: datetime.strptime(re.search(r'd{4}-d{2}-d{2}_d{2}-d{2}-d{2}', x).group(0), '%Y-%m-%d_%H-%M-%S'))
for element in example:
print(element)

输出为:

1A25_%_2019-11-12_12-08-35.IV2
15_LA_2020-11-12_12-08-35.IV2
125_L_2021-11-12_12-08-35.IV2

正如你所看到的,无论名字在日期之前是什么模式(我试图用不同的字符和长度修改它们(,最终它们都是正确排列的。重要的是,除非正则表达式也相应地改变,否则写日期的模式不会改变。

解决方案非常简洁,可能由于使用了嵌套函数而不清楚,我试图解释:
单行函数所做的第一件事是用正则表达式搜索写日期的模式(YYYY-mm-dd_hh-mm-ss(。一旦找到日期,就会将其转换为datatime。所有这些都是在排序函数中的lambda函数中完成的,可以对整个列表进行排序。

显然,您可以将该函数划分为子指令,但概念是这样的。

最新更新