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]
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 【python100案例 - 20】指定范围内高度落下反弹着地次数
- leetcode简单题81-100(python)
- 【Python爬虫】爬取猫眼电影TOP100榜
- Python利用selenium+PhantomJS爬取猫眼电影Top100
- 小白入门_python菜鸟100题(16-20)
- Python爬虫入门教程 60-100 python识别验证码,阿里、腾讯、百度、聚合数据等大公司都这么干
- Python 语感训练100题
- Python面试100题---02
- Python实现1-9数组形成的结果为100的所有运算式的示例
- Python爬虫-爬取猫眼电影Top100榜单
- 用python实现从1加到100的三种方法: for循环,while循环,导入模块法
- Python基础教程(十三):JSON、练习题100题
- Python 100 例 练习实例1
- Python 找出1与100之间的全部“同构数”
- 使用python实现打印所有100以内的所有质数
- python爬取猫眼top100
- 利用python 完成 leetcode 100 相同的树
- Python3基础 list 推导式 生成100以内的偶数列表
- Python下载百度新歌100的代码
- [转]Python下载百度新歌100的代码