有没有一种更具python风格的方法将两个列表中的元素的最大数目合并到on中

2024-06-28 19:44:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python编写一个packet diff工具,使用scapy查找两个pcap文件中的差异,然后以可读的格式输出差异。脚本将每个数据包单独进行比较,并将不同的层/协议/im-not-that-much-of-a-networking-guy-sorry分开进行单独比较。这就是我的困境开始的地方,你不知道有什么层,或者有多少层,或者如果有多个相同的层,或者两个包可能有完全不同的层。我的计划是找出不同层的名称,然后将两个列表粉碎在一起,并使用该列表来知道我应该在两个数据包中查找哪种层。我不太确定这是不是最好的办法,但我真的能想到的就这些了。如果你对如何做有更好的想法,请分享

太长了,读不下去了。 我需要弄清楚如何将两个层名称列表“合并”在一起,以便比较两个数据包

我试着写,但没能得到我想要的。然后我被告知,它看起来像是用python编写的c,为了使它更像python,我完全理解。你知道吗

def get_common_layers(layers_1, layers_2):  # doesn't quite work
    layers_total = []
    i = 0
    while i < len(layers_1):
        temp_count = layers_1.count(layers_1[i])
        if layers_1[i] not in layers_total:
            if layers_1[i] not in layers_2:
                layers_total.extend(layers_1[i:i + temp_count])
            elif layers_1[i] in layers_2:
                if temp_count >= layers_2.count(layers_1[i]):
                    layers_total.extend(layers_1[i:i + temp_count])
        i = i + temp_count
    i = 0
    while i < len(layers_2):
        temp_count = layers_2.count(layers_2[i])
        if layers_2[i] not in layers_total:
            if layers_2[i] not in layers_1:
                layers_total.extend(layers_2[i:i + temp_count])
            elif layers_2[i] in layers_1:
                if temp_count >= layers_1.count(layers_2[i]):
                    layers_total.extend(layers_2[i:i + temp_count])
        i = i + temp_count
    return layers_total

这有点接近,但有点不对劲。 很抱歉,我还不能真正解释我的意思,但是unittest和所需的输入和输出应该能提供更好的图片

期望输入和输出:

layers_1 = ['Ether', 'UDP', 'DNS', 'DNSQR', 'DNSQR', 'DNSQR', 'DNSRR'],
layers_2 = ['Ether', 'TCP', 'DNS', 'DNSRR', 'DNSRR', 'DNSQR'])

layers_total = ['Ether', 'UDP', 'TCP', 'DNS', 'DNSQR', 'DNSQR', 'DNSQR', 'DNSRR', 'DNSRR']

unittest显示的错误截图: https://imgur.com/UFi92jY.png“单元测试”

我要做的事情的截图: https://imgur.com/eMZNX5V.png“示例输出”

(如果没有新帐户,可能会显示图片)


Tags: in列表ifdnslayerscountnot差异