Python字符串在循环中未正确清除

Python字符串在循环中未正确清除,python,list,loops,Python,List,Loops,我正在编写一个脚本,其中我需要浏览一个csv文件,并找到我正在寻找的特定用户第一次登录,以及最后一次注销。我设置了一些循环,它们工作得很好,但是当我清除带有登录/注销时间字符串的列表时,我得到了一个索引超出范围的错误。有人能发现这有什么不正确的地方吗 #this gets the earliest login time for each agent (but it assumes all dates to be the same!) with open(inputFile, 'r') a

我正在编写一个脚本,其中我需要浏览一个csv文件,并找到我正在寻找的特定用户第一次登录,以及最后一次注销。我设置了一些循环,它们工作得很好,但是当我清除带有登录/注销时间字符串的列表时,我得到了一个索引超出范围的错误。有人能发现这有什么不正确的地方吗

    #this gets the earliest login time for each agent (but it assumes all dates to be the same!)
with open(inputFile, 'r') as dailyAgentLog:
    csv_read = csv.DictReader(dailyAgentLog)
    firstLoginTime = []
    lastLogoutTime = []
    outputLine = []
    while x < len(agentName):
        for row in csv_read:
            if row["Agent"] == agentName[x]:
                firstLoginTime.append(datetime.strptime(row["Login Time"], '%I:%M:%S %p'))
                lastLogoutTime.append(datetime.strptime(row["Logout Time"], '%I:%M:%S %p'))
        firstLoginTime.sort()
        lastLogoutTime.sort()
        outputLine = [agentName[x], agentLogin[x], agentExtension[x], row["Login Date"], firstLoginTime[0], row["Logout Date"], lastLogoutTime[-1]]
        print(f'Agent {agentName[x]} first login was {firstLoginTime[0]} and last logout {lastLogoutTime[-1]}.')
        fileLines.append(outputLine)

        x += 1

        firstLoginTime.clear() #this should be emptying/clearing the list at the end of every iteration
        lastLogoutTime.clear()
#这将获取每个代理的最早登录时间(但它假定所有日期都相同!)
打开(输入文件“r”)作为dailyAgentLog:
csv_read=csv.DictReader(dailyAgentLog)
firstLoginTime=[]
lastLogoutTime=[]
outputLine=[]
而x
问题在于,在第二次迭代和后续迭代中,csv中的行的
读取:
循环不会执行,因为没有剩余的内容可读取。因此,您永远不会在后续迭代中填写
firstLoginTime
lastLoginTime
列表,并且索引失败

如果文件不太大,可以在迭代之前将其读入列表:

csv_read = list(csv.DictReader(dailyAgentLog))
如果它太大而无法保存在内存中,请将

dailyAgentLog.seek(0)
在循环体的末尾

此外,您可以使用
min()
max()
,而不是对列表进行排序:

我建议你用

for x in range(len(agentName)):

而不是
while
和increment.

您能分享您的输入、预期输出和完整错误吗?请参阅。您只能在
csv\u read
中迭代一次。当您到达文件末尾时,将不会有任何内容可供读取,除非您执行
dailyAgentLog.seek(0)
与问题无关,但Pythonistas更喜欢
snake\u case\u variables
而不是
camelcaseviables
。这不是一个要求,但如果你遵循建议,你的代码会看起来更好。非常感谢,我很感激。我已经有一段时间没有涉足编程了,所以我正在努力摆脱这种困境。我感谢你的提示和时间来帮助我!
for x in range(len(agentName)):