python map 函数
来源:互联网 发布:上海一手房成交数据 编辑:程序博客网 时间:2024/05/21 03:19
假设有一个数列,如何把其中每一个元素都翻倍?
第一种写法:
lst_1 = [1,2,3,4,5,6]
lst_2 = []
for item in lst_1:
lst_2.append(item * 2)
print lst_2
第二种写法:
lst_1 = [1,2,3,4,5,6]
lst_2 = [i * 2 for i in lst_1]
print lst_2
第三种写法: map函数
lst_1 = [1,2,3,4,5,6]
def double_func(x):
return x * 2
lst_2 = map(double_func, lst_1)
print lst_2
map 是 Python 自带的内置函数,它的作用是把一个函数应用在一个(或多个)序列上,把列表中的每一项作为函数输入进行计算,再把计算的结果以列表的形式返回。
map 的第一个参数是一个函数,之后的参数是序列,可以是 list、tuple。
所以刚刚那个问题也可以写成:
lst_1 = (1,2,3,4,5,6)
lst_2 = map(lambda x: x * 2, lst_1)
print lst_2
这里原数据改为了元组,函数用 lambda 表达式替代。此外,当 map 中的函数为 None 时,结果将会直接返回参数组成的列表。如果只有一组序列,会返回元素相同的列表,如果有多组数列,将会返回每组数列中,对应元素构成的元组所组成的列表。听上去很绕口是不是……代码试试看就明白了:
lst_1 = [1,2,3,4,5,6]
lst_2 = [1,3,5,7,9,11]
lst_3 = map(None, lst_1)
print lst_3
lst_4 = map(None, lst_1, lst_2)
print lst_4
- python map()函数
- Python-map()函数
- python map函数用法
- Python中map()函数
- python中map()函数
- python中的map()函数
- python map 函数
- python---map函数
- Python中的map函数
- python:map函数练习
- python map函数
- python map函数
- python-内置函数map()
- python-内置函数map()
- python中的map函数
- python map函数
- python map()函数
- Python中map函数
- Latex Command for argmin or argmax?
- 【韩顺平Linux笔记02】用户管理和目录结构
- MySQL 之 ROUND 函数四舍五入的陷阱
- 洛谷 P1739 表达式括号匹配
- LayoutInflater的一些理解
- python map 函数
- python3.5以上 爬虫 (模块化)
- 常见异常以及处理问题办法
- 我的生活(四)-误打误撞入行It
- nginx try_files用法 及Nginx location的一些配置
- setTimeout与setInterval方法的区别
- BZOJ1453: [Wc]Dface双面棋盘
- 洛谷 P1160 队列安排
- utf-8编码格式