Python:TypeError:int()参数必须是字符串或数字,而不是';IPV4网络&x27;

Python:TypeError:int()参数必须是字符串或数字,而不是';IPV4网络&x27;,python,python-2.7,Python,Python 2.7,我试图从csv中读取IP地址,将其转换为IP范围,并按每个类别对其进行排列/分组 下面是我的代码: def create_range(ip_addresses): groups = [] for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i, x): i-int(x)): group = map(operator.itemgetter(1), g) if len

我试图从csv中读取IP地址,将其转换为IP范围,并按每个类别对其进行排列/分组

下面是我的代码:

def create_range(ip_addresses):
    groups = []
    for _, g in itertools.groupby(enumerate(sorted(ip_addresses)), lambda (i, x): i-int(x)):
       group = map(operator.itemgetter(1), g)
       if len(group) > 1:
           groups.append("{}-{}".format(group[0], str(group[-1])))
       else:
           groups.append(str(group[0]))
    return groups

ips = collections.defaultdict(list)

with open('some.csv') as csv_file:
    file_reader = csv.reader(csv_file)
    next(file_reader)
    for (ip, cat, typ) in file_reader:
        ip = ipaddress.IPv4Network(unicode(ip.strip()))
        cat = cat.strip()
        ips[cat.strip()].append(ip)
    resultIPranges = {org: create_range(ip_range) for cat, ip_range in ips.items()}
我的CSV如下所示:

csv_file = """ip, cat, typ
              50.102.182.2, myCompany, blue
              52.102.182.4, myCompany, blue
              52.102.182.1, myCompany, blue
              52.102.182.5, myCompany, blue
              52.102.182.3, myCompany, blue
              27.101.178.17, myCompany, blue
              27.101.178.16, hisComp, red
              27.101.178.15, hisComp, red
              23.201.165.7, hisComp, red
              55.200.162.10, hisComp, red
              55.200.162.12, hisComp, red
              55.200.162.13, hisComp, red
              55.200.162.11, hisComp, red
              30.101.102.4, hisComp, red
"""
当前问题/错误:

对于itertools.groupby(枚举(排序的(ip_地址))中的g, lambda(i,x):i-int(x)):TypeError:int()参数必须是字符串 或一个数字,而不是“IPV4网络”


据我所知,您的
x
是一个
ipv4网络
实例,而不是
int
;因此
int(x)
无法将其转换为int

可以转换的东西是
IPv4Address
实例;所以我的目标是你应该改变

 ip = ipaddress.IPv4Network(unicode(ip.strip()))


–opalczynski

据我所知,您的x是一个IPV4网络实例,而不是int;所以int(x)不能将其转换为int;可以转换的东西是IPv4Address实例;因此,我的想法是您应该将ip=ipaddress.IPv4Network(unicode(ip.strip())更改为ip=ipaddress.IPv4Address(unicode(ip.strip()))是的,您是对的。这就是问题所在。非常感谢。
 ip = ipaddress.IPv4Address(unicode(ip.strip()))