简体   繁体   English

地图未打开元组

[英]Map not unpacking tuples

I have this simple formula that converts an IP to a 32 bits integer: 我有一个简单的公式,可以将IP转换为32位整数:

(first octet * 256**3) + (second octet * 256**2) + (third octet * 256**1) + (fourth octet)

I made a program that does that: 我做了一个程序来做到这一点:

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

And it works as intended. 它按预期工作。

Then I tried to make a one-liner, just for the sake of doing it. 然后,为了做到这一点,我尝试制作单线。

sum(map(lambda x, y: int(x) * 256 ** (3 - y), enumerate(ip.split("."))))

But this raises 但这引起了

TypeError: <lambda>() takes exactly 2 arguments (1 given)

So the tuple (y, x) is not being unpacked. 因此,元组(y,x)不会被解包。 I can fix this with 我可以解决这个问题

sum(map(lambda x: int(x[1]) * 256 ** (3 - x[0]), enumerate(ip.split("."))))

But this seems uglier (one liners are always ugly) 但这似乎比较丑陋(一个衬里总是丑陋的)

I even tried using a list comprehensions, but map still doesn't unpack the values. 我什至尝试使用列表推导,但是map仍然没有解压这些值。

Is this a feature or am I doing something wrong? 这是功能还是我做错了什么? Is there a specific way to do this? 有没有特定的方法可以做到这一点?

The equivalent generator expression would be 等效的生成器表达式为

>>> 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不会解包,但星图会:

sum(starmap(lambda x, y: int(y) * 256 ** (3 - x), enumerate(ip.split("."))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM