【问题标题】:Is there a more pythonic way to merge the maximum number of a element of two lists into one是否有一种更 Pythonic 的方法可以将两个列表中元素的最大数量合并为一个
【发布时间】:2019-10-17 06:30:46
【问题描述】:

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

tl;博士 我需要弄清楚如何将两个图层名称列表“合并”在一起,以便比较两个数据包

我试图写它,但我无法完全得到我想要的。然后我被告知它看起来像用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“单元测试”

我正在尝试实际执行的操作的屏幕截图: https://imgur.com/eMZNX5V.png“example_output”

(本来会显示照片但新帐户)

【问题讨论】:

  • 这个问题很难解读。最终看起来你想要某种列表或集合操作,可能两者都有一些嵌套方面。如果您要将问题降低到最基本的水平(例如,如果我能做到 this 那么我就可以将它应用于我的情况)即minimal reproducible example 你会可能会在几分钟内得到答复。

标签: python list scapy packet


【解决方案1】:

您是否在寻找两个列表的联合?这应该有效:

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

【讨论】:

  • set.union 的第一个参数(在 self 之后)不必是一个集合,它可以是任何可迭代的。
猜你喜欢
  • 2011-08-15
  • 2020-07-05
  • 2018-11-27
  • 1970-01-01
  • 2015-07-06
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多