您的位置:首页 > 编程语言 > Python开发

python 中0到100

2020-01-15 11:09 2151 查看

一、方法

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]
  • 点赞
  • 收藏
  • 分享
  • 文章举报
浪子哥学习笔记 发布了13 篇原创文章 · 获赞 0 · 访问量 128 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: