python3基础学习-2023年06月15日-accmulate,bit_count

from itertools import accumulate
from operator import add, xor, sub


def func(a: int, b: int) -> int:
    return 1


if __name__ == "__main__":
    # 1.itertools.accumulate学习
    a = [1, 2, 3, 4, 5, 6]
    print(list(accumulate(iterable=a)))  # [1, 3, 6, 10, 15, 21]
    print(list(accumulate(iterable=a, func=sub)))  # [1, -1, -4, -8, -13, -19]
    print(list(accumulate(iterable=a, func=add, initial=0)))  # [0, 1, 3, 6, 10, 15, 21]
    b = list(accumulate(iterable=a, func=add, initial=0))
    print(b)  # [0, 1, 3, 6, 10, 15, 21]
    # 2. 对bit_count学习
    print(b[5])  # 15
    print(bin(b[5]))  # 0b1111
    print(b[5].bit_count())  # 4

accumulate 积累

官方说明地址: https://docs.python.org/3/library/itertools.html#itertools.accumulate

创建一个迭代器,返回累积汇总值或其他双目运算函数的累积结果值(通过可选的 func 参数指定)。

如果提供了 func,它应当为带有两个参数的函数。 输入 iterable 的元素可以是能被 func 接受为参数的任意类型。
(例如,对于默认的加法运算,元素可以是任何可相加的类型包括 Decimal 或 Fraction。)

通常,输出的元素数量与输入的可迭代对象是一致的。 但是,如果提供了关键字参数 initial,则累加会以 initial
值开始,这样输出就比输入的可迭代对象多一个元素。

3.2 新版功能.

在 3.3 版更改: 增加可选参数 func 。

在 3.8 版更改: 添加了可选的 initial 形参。

bit_count

官方地址: https://docs.python.org/3/library/stdtypes.html?highlight=bit_count#int.bit_count

返回整数的绝对值的二进制表示中 1 的个数。也被称为 population count。
等价于:

def bit_count(self):
    return bin(self).count("1")

3.10 新版功能.Ï

猜你喜欢

转载自blog.csdn.net/JianShengShuaiest/article/details/131226402
今日推荐