地图不拆包元组
Map not unpacking tuples
我有一个将 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 仍然没有解包值。
这是一个功能还是我做错了什么?有具体的方法吗?
等效的生成器表达式为
>>> ip = "128.32.10.1"
>>> sum(int(base) * 256 ** (3 - exp) for exp, base in enumerate(ip.split('.')))
2149583361
以下内容可能更简洁(使用我在评论中建议的 reduce()
)
reduce(lambda a, b: a * 256 + int(b), ip.split("."), 0)
是的,map
不解压,但 starmap 解压:
sum(starmap(lambda x, y: int(y) * 256 ** (3 - x), enumerate(ip.split("."))))
我有一个将 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 仍然没有解包值。
这是一个功能还是我做错了什么?有具体的方法吗?
等效的生成器表达式为
>>> ip = "128.32.10.1"
>>> sum(int(base) * 256 ** (3 - exp) for exp, base in enumerate(ip.split('.')))
2149583361
以下内容可能更简洁(使用我在评论中建议的 reduce()
)
reduce(lambda a, b: a * 256 + int(b), ip.split("."), 0)
是的,map
不解压,但 starmap 解压:
sum(starmap(lambda x, y: int(y) * 256 ** (3 - x), enumerate(ip.split("."))))