映射不解包元组

时间:2015-06-01 12:37:52

标签: 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 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仍然没有解压缩值。

这是一个功能还是我做错了什么?有没有具体的方法来做到这一点?

3 个答案:

答案 0 :(得分:1)

等效的生成器表达式是

>>> ip = "128.32.10.1"
>>> sum(int(base) * 256 ** (3 - exp) for exp, base in enumerate(ip.split('.')))
2149583361

答案 1 :(得分:1)

以下内容可能有点整洁(正如我在评论中所建议的那样使用reduce()

reduce(lambda a, b: a * 256 + int(b), ip.split("."), 0)

答案 2 :(得分:0)

是的,"image" == c ? wc(b, d, e) : "xhr" == c && wd(b, d, e) || "beacon" == c && x(b, d, e) || ba(b, d, e) 不会解包,但starmap会:

map