python3:set和itertools.groupby产生不同的结果?

2024-10-01 02:21:16 发布

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

我想用IPWhois解析一些Apache访问日志

我想根据asn_description字段对IPWhois结果进行分组

下面的片段中的setitertools.groupby()的结果是否不同

descs = set()

with open(RESULTSFILE, 'a+') as r:
    for description, items in groupby(results, key=lambda x: x['asn_description']):
        print('ASN Description: ' + description)
        descs.add(description)

print(descs)

例如

ASN Description: GOOGLE - Google LLC, US
ASN Description: AVAST-AS-DC, CZ
ASN Description: FACEBOOK - Facebook, Inc., US
ASN Description: AVAST-AS-DC, CZ
ASN Description: AMAZON-AES - Amazon.com, Inc., US
ASN Description: FACEBOOK - Facebook, Inc., US
ASN Description: AMAZON-02 - Amazon.com, Inc., US
ASN Description: AMAZON-02 - Amazon.com, Inc., US
ASN Description: GOOGLE - Google LLC, US
ASN Description: GOOGLE-2 - Google LLC, US
ASN Description: AMAZON-02 - Amazon.com, Inc., US
{'FACEBOOK - Facebook, Inc., US', 'AVAST-AS-DC, CZ', 'AMAZON-AES - Amazon.com, Inc., US', 'GOOGLE-2 - Google LLC, US', 'GOOGLE - Google LLC, US', 'AMAZON-02 - Amazon.com, Inc., US',

Tags: comamazonasgoogledescriptiondcincus
1条回答
网友
1楼 · 发布于 2024-10-01 02:21:16

将代码更改为以下内容,然后重试。如果不需要items,可以使用_替换它,将其从for循环中删除

import itertools
descs = dict()

with open(RESULTSFILE, 'a+') as r:
    for i, (description, items) in enumerate(itertools.groupby(results, key=lambda x: x['asn_description'])):
        print('ASN Description: ' + description)
        descs.update({i: description})

print(descs)

相关问题 更多 >