[英]How can I assign a tuple to a dictionary key in Python?
我有这样的数据:
(asn,prefix,ip,count_domain)
(15967, '77.55.0.0/16', '77.55.236.177', 10)
(15967, '77.55.0.0/16', '77.55.236.178', 11)
(20773, '195.225.104.0/22', '195.225.104.182', 22)
(20773, '195.225.104.0/22', '195.225.104.181', 10)
(8560, '87.106.0.0/16', '87.106.1.10', 15)
(20454, '198.24.128.0/19', '198.24.143.43', 89)
(20454, '198.24.128.0/19', '198.24.143.45', 608)
(20454, '198.24.128.0/19', '198.24.143.46', 32)
(31815, '216.70.96.0/20', '216.70.102.229', 12)
(31815, '216.70.96.0/20', '216.70.102.228', 20)
我想提取每个asn和前缀的一些IP和域,如下所示:
(asn,prefix,count_ip,count_domain)
(15967, '77.55.0.0/16', 2, 21)
(20773, '195.225.104.0/22', 2, 32)
(8560, '87.106.0.0/16', 1, 15)
(20454, '198.24.128.0/19', 3, 729)
(31815, '216.70.96.0/20', 2, 32)
我当前的python脚本是这个,但是字典中语法错误导致我出错。 有人可以帮忙吗?
count = {}
with open (output,'w') as w:
with open (file , 'r') as f:
for line in f :
if line.strip() != '':
domain = int(line.split('|')[1])
if domain>=10:
ip = line.split('|')[0]
try:
prefix = asndb.lookup(ip)[1]
asn = asndb.lookup(ip)[0]
if [asn,prefix] not in count:
count[asn,prefix] = count
else:
count[asn,prefix] += count
# print(asn,prefix,ip,domain)
except:
print line
pass
错误:
if asn,prefix not in count:
^
SyntaxError: invalid syntax
使用asn
和prefix
的值显式分配一个元组,然后使用该元组作为键(我认为这是根据标题您要执行的操作)。 另外,如果您以我认为的使用方式使用字典,请将计数增加1(而不是尝试将对字典的引用分配为值)。
prefix = asndb.lookup(ip)[1]
asn = asndb.lookup(ip)[0]
key = (asn, prefix)
if key not in count:
count[key] = 1
else:
count[key] += 1
编辑以修复由@AshwiniChaudhary捕获的愚蠢错字
if [asn,prefix] not in count:
列表类型不能成为字典的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.