python 中0到100

一、方法

1、此方式只适用于数字类型

result = sum(range(101))

2、+=

    result = 0
    for i in range(101):
        result += i

3、reduce

from functools import reduce
result = reduce(lambda x,y:x+y, range(101))

4、accumulate

from itertools import accumulate
x = list(accumulate(range(101)))#[0, 1, 3, 6, 10, 15, 21, ... , 4950, 5050]
result = x[-1]

二、推广

问题:

dataB = [[1,2], [4,5], [6,7]] # 要求输出 [1, 2, 4, 5, 6, 7]

1、reduce

from functools import reduce
result = reduce(lambda x,y:x+y, dataB)

2、chain

from itertools import chain
result = list(chain(*dataB)) # 此方法只是起到连接多个 itertools 的作用

3、+= 或者 extend

result = []
for data in dataB:
    # 以下两种方式都可以
    # result += data
    result.extend(data)

4、accumulate

from itertools import accumulate
result = list(accumulate(dataB))[-1]
发布了26 篇原创文章 · 获赞 4 · 访问量 742

猜你喜欢

转载自blog.csdn.net/qq_36072270/article/details/103496400