Python 映射不解包元组
我有一个简单的公式,可以将IP转换为32位整数:Python 映射不解包元组,python,python-2.7,dictionary,iterable-unpacking,Python,Python 2.7,Dictionary,Iterable Unpacking,我有一个简单的公式,可以将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
(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)
但这似乎更难看(一句台词总是难看)
我甚至尝试使用列表理解,但map仍然没有解压这些值
这是一个功能还是我做错了什么?有没有具体的方法来实现这一点?等效的生成器表达式是
>>> ip = "128.32.10.1"
>>> sum(int(base) * 256 ** (3 - exp) for exp, base in enumerate(ip.split('.')))
2149583361
等效的生成器表达式为
>>> ip = "128.32.10.1"
>>> sum(int(base) * 256 ** (3 - exp) for exp, base in enumerate(ip.split('.')))
2149583361
以下内容可能更整洁一些(使用
reduce()
,正如我在评论中建议的那样)
以下内容可能更整洁一些(使用
reduce()
,正如我在评论中建议的那样)
则,
map
不会解包,但会:
则,
map
不会解包,但会:
我认为您使用的是
map()
,而您真正想要的是reduce()
。lambda函数应该是lambda(x,y):int(x)*256**(3-y)
-lambda x,y
相当于def(x,y):
:您正在定义一个包含两个参数的函数,而不是一个元组。@PascalBugnon:这在Python 2上有效,但在Python 3中删除了该功能。我认为您使用的是map()
,而您真正想要的是reduce()
。lambda函数应该是lambda(x,y):int(x)*256**(3-y)
-lambda x,y
相当于def(x,y):
:您正在定义一个接受两个参数的函数,而不是一个元组。@PascalBugnon:该函数在Python 2上工作,但在Python 3中该功能已被删除。requires来自itertools import starmap
语句requires来自itertools import starmap
语句
reduce(lambda a, b: a * 256 + int(b), ip.split("."), 0)
sum(starmap(lambda x, y: int(y) * 256 ** (3 - x), enumerate(ip.split("."))))