我能把这个循环转换成一个映射吗(λx:…)不知怎么的?

2024-04-26 10:51:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试优化一个方法,该方法计算1中每个数的二进制表示形式中的0 -> num个数

# Example of how the below works, for clarity
#
# base => [0,1,1,2,1,2,2]
# index => 7
#
#   {7} --
#       bin(7)              :   111
#       bin(7-1)            :   110
#       111 & 110           :   110 (6)
#       append(base[6]+1)   :   append(3)
#     //end 7
#
# base => [0,1,1,2,1,2,2,3]

def countBits(num):
    index = 1
    base = [0]

    while(index <= num):
        base.append(base[(index & (index - 1))]+1)
        index += 1

    return base

我想知道是否有一种方法可以将while循环转换成可以就地完成而不是循环的东西?我的第一个想法是。。。你知道吗

base.append(map(lambda index: base[(index & (index -1))]+1, num))

但这根本没用。。base保持不变。我想我只是不完全理解map(lambda x:...)语法的作用。我只用过几次,直接打电话。你知道吗


Tags: of方法lambdamapbaseindexbinexample
1条回答
网友
1楼 · 发布于 2024-04-26 10:51:29

也许你想要这样的东西?你知道吗

num = 11

base = [0]
for _ in range(1, num):
    base.extend(map(lambda index: base[(index & (index -1))] + 1, [_]))

结果:

[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2]

相关问题 更多 >