gpt4 book ai didi

python - 识别字典中的重复值并打印在表格中

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:54 24 4
gpt4 key购买 nike

我有一个字典 (d),其中每个键可以有多个值(作为列表附加)。

例如,字典具有以下两个键值对,其中一个具有重复值,而另一个则没有:

SPECIFIC-THREATS , ['5 SPECIFIC-THREATS Microsoft Windows print spooler little endian DoS attempt', '4 SPECIFIC-THREATS obfuscated RealPlayer Ierpplug.dll ActiveX exploit attempt', '4 SPECIFIC-THREATS obfuscated RealPlayer Ierpplug.dll ActiveX exploit attempt']

TELNET , ['1 TELNET bsd exploit client finishing']

我想遍历整个字典,检查是否有任何键有重复值,然后将结果打印在一个表中,该表将键、重复值的数量、值(出现多次)等作为列。

这是我到目前为止所拥有的:

import texttable
import collections

def dupechecker():

t = texttable.Texttable()
for key, value in d.iteritems():
for x, y in collections.Counter(value).items():
if y > 1:
t.add_rows([["Category", "Number of dupe values", "Value which appears multiple times"], [key, y, x]])
print t.draw()

它可以工作,但没有任何重复值的键(即本例中的 TELNET)不会出现在表输出中(因为该表是在 if 条件语句中打印的)。这就是我得到的:

+-------------------------+-------------------------+-------------------------+
| Category | Number of dupe values | Value which appears |
| | | multiple times |
+=========================+=========================+=========================+
| SPECIFIC-THREATS | 2 | 4 SPECIFIC-THREATS |
| | | obfuscated RealPlayer |
| | | Ierpplug.dll ActiveX |
| | | exploit attempt |
+-------------------------+-------------------------+-------------------------+

无论如何,我可以跟踪每个键的有趣参数(重复值的数量和出现多次的值),然后将它们打印在一起。我希望输出如下:

+-------------------------+-------------------------+-------------------------+
| Category | Number of dupe values | Value which appears |
| | | multiple times |
+=========================+=========================+=========================+
| SPECIFIC-THREATS | 2 | 4 SPECIFIC-THREATS |
| | | obfuscated RealPlayer |
| | | Ierpplug.dll ActiveX |
| | | exploit attempt |
+-------------------------+-------------------------+-------------------------+
| TELNET | 0 | |
| | | |
| | | |
| | | |
+-------------------------+-------------------------+-------------------------+

更新

已解决

最佳答案

只需更改您的 dupechecker 即可为“非重复项”添加行,但每个类别仅添加一次,在循环之前添加标题并在完成后打印表格。

def dupechecker():

t = texttable.Texttable()
t.header(["Category", "Number of dupe values", "Value which appears multiple times"])
for key, value in d.iteritems():
has_dupe = False
for x, y in collections.Counter(value).items():
if y > 1:
has_dupe = True
t.add_row([key, y, x])
if not has_dupe:
t.add_row([key, 0, ''])
print t.draw()

关于python - 识别字典中的重复值并打印在表格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com