我有一个简单的公式,它将IP转换为32位整数:
(first octet * 256**3) + (second octet * 256**2) + (third octet * 256**1) + (fourth octet)我做了一个这样的程序:
def ip_to_int32(ip):
# split values
ip = ip.split(".")
# formula to convert to 32, x is the octet, y is the power
to_32 = lambda x, y: int(x) * 256** (3 - y)
# Sum it all to have the int32 of the ip
# reversed is to give the correct power to octet
return sum(
to_32(octet, pwr) for pwr, octet in enumerate(ip)
)
ip_to_int32("128.32.10.1") # --> 2149583361它的工作方式和预期一样。
然后,我试着做一个单线,只是为了做这个。
sum(map(lambda x, y: int(x) * 256 ** (3 - y), enumerate(ip.split("."))))但这增加了
TypeError: <lambda>() takes exactly 2 arguments (1 given)所以元组(y,x)没有被解压。我可以用
sum(map(lambda x: int(x[1]) * 256 ** (3 - x[0]), enumerate(ip.split("."))))但这看起来更丑(一条线总是丑陋的)
我甚至尝试使用列表理解,但map仍然没有打开这些值。
,这是一个特性,还是我做错了什么?有什么特别的方法吗?
发布于 2015-06-01 12:44:16
下面的内容可能更整洁一些(正如我在评论中建议的那样,使用reduce() )
reduce(lambda a, b: a * 256 + int(b), ip.split("."), 0)发布于 2015-06-01 13:14:20
诚然,map不解压缩,但星图解压缩:
sum(starmap(lambda x, y: int(y) * 256 ** (3 - x), enumerate(ip.split("."))))发布于 2015-06-01 12:40:42
等效的生成器表达式将是
>>> ip = "128.32.10.1"
>>> sum(int(base) * 256 ** (3 - exp) for exp, base in enumerate(ip.split('.')))
2149583361https://stackoverflow.com/questions/30573681
复制相似问题