簡體   English   中英

如何遍歷列表並組合數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM