我如何将此项目附加到同一列表,而不是每次循环时都创建一个新列表?

问题描述 投票:1回答:1

这是我当前的代码:

fd = open('/var/log/secure.log')
syslog = fd.readlines()

countTable = {} # initialization of a dictionary
for line in syslog:
        data = line.split()  
        if len(data) >= 15:
                if data[14] in ['user=root']:
                        intrusions = []
                        ip = data[13].replace('rhost=', "")
                        intrusions.extend(ip)
                        print "intruder:", intrusions

这是我得到的输出:

intruder: ['218.92.0.201']
intruder: ['222.186.173.142']
intruder: ['222.186.173.142']
intruder: ['222.186.173.142']
intruder: ['218.92.0.201']
intruder: ['218.92.0.201']
intruder: ['222.186.30.218']
intruder: ['218.92.0.201']

我如何将所有这些IP放入相同的“入侵”列表?

谢谢!

python list loops append
1个回答
0
投票

您只需要在第一个循环之前移动intrusions = []

countTable = {} # initialization of a dictionary

intrusions = []
for line in syslog:
        data = line.split()  
        if len(data) >= 15:
                if data[14] in ['user=root']:

                        ip = data[13].replace('rhost=', "")
                        intrusions.extend(ip)
                        print "intruder:", intrusions
© www.soinside.com 2019 - 2024. All rights reserved.