[英]How to iterate through a list and combine the data
我希望遍历具有源 IP、目标 IP、时间和数据包长度的列表。 如果有任何行包含相同的源 IP 和目标 IP,我需要删除重复的行并显示开始时间、停止时间和总数据包长度。
def combine_data(source, dest, time, length):
CombinePacket = []
CombinePacket = [(source[i], dest[i], time[i], length[i]) for i in range(len(source))]
counter = 0
line = []
for i, j in zip(source, dest):
if(source[counter] and dest[counter] == source[counter+1] and dest[counter+1]):
print(CombinePacket[counter-1], CombinePacket[counter])
counter+=1
return 0
(['172.217.2.161'], ['10.247.15.39'], '13:25:31.044180', '0')
(['172.217.2.161'], ['10.247.15.39'], '13:25:31.044371', '46')
我期待合并这些行,它应该看起来像这样:
(['172.217.2.161'], ['10.247.15.39'], '13:25:31:044180', '13:25:31:044371', '46')
您没有向测试代码添加一些数据,我不知道这是否是您的问题,但您错误地比较了
source[counter] and dest[counter] == source[counter+1] and dest[counter+1]
因为这意味着
(source[counter]) and (dest[counter] == source[counter+1]) and (dest[counter+1])
您必须分别比较每个元素
source[counter] == source[counter+1] and dest[counter] == dest[counter+1]
或者您可以比较元组或列表
(source[counter], dest[counter]) == (source[counter+1], dest[counter+1])
而不是zip(source, dest):
您可以使用zip(CombinePacket, CombinePacket[1:])
并且您将拥有两个可用于创建新行的组合行。 您将获取所有数据作为列表,以便您可以将列表与[source, dest]
进行比较
results = []
for x, y in zip(combine_packet, combine_packet[1:]):
if (x[0:2] == y[0:2]): # `[source, dest]`
data = [x[0], x[1], x[2], y[2], y[3]]
print(data) # (['172.217.2.161'], ['10.247.15.39'], '13:25:31:044180', '13:25:31:044371', '46')
results.append(data)
但我不知道是否可以有三行具有相同的source, dest
以及您对这三行的期望结果。
def combine_data(source, dest, time, length):
combine_packet = list(zip(source, dest, time, length))
results = []
for x, y in zip(combine_packet, combine_packet[1:]):
if (x[0:2] == y[0:2]):
#print(x) # (['172.217.2.161'], ['10.247.15.39'], '13:25:31.044180', '0')
#print(y) # (['172.217.2.161'], ['10.247.15.39'], '13:25:31.044371', '46')
data = [x[0], x[1], x[2], y[2], y[3]]
print(data) # (['172.217.2.161'], ['10.247.15.39'], '13:25:31:044180', '13:25:31:044371', '46')
results.append(data)
return results
source = [['172.217.2.161'], ['172.217.2.161'], ['0.0.0.0']]
dest = [['10.247.15.39'], ['10.247.15.39'], ['10.247.15.39']]
time = ['13:25:31.044180', '13:25:31.044371', '13:25:31.044371']
length = ['0', '46', '123']
combine_data(source, dest, time, length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.