Python去除输出的重复项

2024-07-04 08:25:40 发布

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

我有一个简单的python代码,用于获取域的NS记录:

#!/usr/bin/python
import socket
import dns.resolver
domain = 'google.com'
resp = dns.resolver.query(domain, 'NS')
for d in resp:
    ns = d.to_text()
    nsip = socket.gethostbyname(ns)
    print ns, nsip

样本结果如下:

ns2.google.com. 216.239.34.10
ns1.google.com. 216.239.32.10
ns3.google.com. 216.239.36.10
ns4.google.com. 216.239.38.10
ns5.google.com. 216.5.5.5

但我想从输出中删除重复打印的IP,如下所示:

IP: 216.239.32.10
    ns2.google.com., ns1.google.com., ns3.google.com., ns4.google.com.

IP: 216.5.5.5
    ns5.google.com. 

我该怎么做?你知道吗


Tags: importipcomdnsdomaingooglesocketresp
1条回答
网友
1楼 · 发布于 2024-07-04 08:25:40

你可以使用defaultdict

In [10]: from collections import defaultdict
In [11]: ns = [['ns2.google.com.', '216.239.32.10'], ['ns1.google.com.', '216.239.32.10'], ['ns3.google.com.', '216.239.36.10'], ['ns4.google.c
    ...: om.', '216.239.38.10'], ['ns5.google.com.', '216.5.5.5']]

In [12]: d = defaultdict(list)
In [13]: for v,k in ns:
    ...:     d[k].append(v)

In [14]: print d
Out[14]: 
defaultdict(list,
            {'216.239.32.10': ['ns2.google.com.', 'ns1.google.com.'],
             '216.239.36.10': ['ns3.google.com.'],
             '216.239.38.10': ['ns4.google.com.'],
             '216.5.5.5': ['ns5.google.com.']})

要打印的输出

In [16]: for k,v in d.items():
    ...:     print "IP: {}".format(k)
    ...:     print "\t{}".format(', '.join(v))
    ...:     
IP: 216.239.36.10
    ns3.google.com.
IP: 216.239.32.10
    ns2.google.com., ns1.google.com.
IP: 216.5.5.5
    ns5.google.com.
IP: 216.239.38.10
    ns4.google.com.

        ...:     

相关问题 更多 >

    热门问题