繁体   English   中英

是否有更多pythonic方法将两个列表的元素的最大数量合并为一个

[英]Is there a more pythonic way to merge the maximum number of a element of two lists into one

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

tl; dr我需要弄清楚如何“合并”两个图层名称列表,以便我可以比较两个数据包

我试着写它,但我无法得到我想要的东西。 然后我被告知它看起来像用python编写的c并使它更加pythonic,我完全理解。

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

这有点接近,但有点偏。 对不起,我真的无法解释我的意思,但是单位测试和所需的输入和输出应该给出更好的图片。

所需的输入和输出:

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 “unittest”

我正在尝试实际做的截图: https//imgur.com/eMZNX5V.png “example_output”

(会有照片出现但新帐户)

你在寻找两个名单的联盟吗? 这应该工作:

layers_total = list(set(layers_1).union(set(layers_2)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM