本文介绍了Python词典列表仅查看最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

努力弄清楚为什么它不起作用.它应该.但是,当我创建字典列表然后浏览该列表时,我只会看到列表中的最后一个条目:

Struggling to figure out why this doesn't work. It should. But when I create a list of dictionaries and then look through that list, I only ever see the final entry from the list:

alerts = []
alertDict = {}
af=open("C:\snort.txt")

for line in af:
    m = re.match(r'([0-9/]+)-([0-9:.]+)\s+.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})\s+->\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})', line)
    if m:
        attacktime = m.group(2)
        srcip = m.group(3)
        srcprt = m.group(4)
        dstip = m.group(5)
        dstprt = m.group(6)
        alertDict['Time'] = attacktime
        alertDict['Source IP'] = srcip
        alertDict['Destination IP'] = dstip
    alerts.append(alertDict)

for alert in alerts:
    if alert["Time"] == "13:13:42.443062":
        print "Found Time"

推荐答案

您在脚本的开头精确地创建了一个字典,然后将该字典重复添加到列表中多次.

You create exactly one dict at the beginning of the script, and then append that one dict to the list multiple times.

通过将初始化移到循环内部,尝试创建多个单独的字典.

Try creating multiple individual dicts, by moving the initialization to the inside of the loop.

alerts = []
af=open("C:\snort.txt")

for line in af:
    alertDict = {}
    #rest of loop goes here

这篇关于Python词典列表仅查看最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 16:12
查看更多