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