[python] List Comprehension
来源:互联网 发布:淘宝特卖女装清仓 编辑:程序博客网 时间:2024/05/10 21:27
- List Comprehension
- Set comprehension
- Dictionary Comprehension
1. List Comprehension
List comprehension is to creat a new list quickly. Example:
# list comprehension>>> mylist = [1,2,2,3,4,4]>>> newlist1 = [x**2 for x in mylist] #square>>> newlist1[1, 4, 4, 9, 16, 16]>>> newlist2 = [x+1 for x in mylist if x%2==0]>>> newlist2[3, 3, 5, 5]
2. Set comprehension
The difference of list and set is that elements in set are unique while list not. Example:
# set comprehension>>> newset = {x+1 for x in mylist}>>> newsetset([2, 3, 4, 5])
an alternative solution is
>>> newlist3 = [x+1 for x in mylist]>>> newlist3[2, 3, 3, 4, 5, 5]>>> newset1 = set(newlist3)>>> newset1set([2, 3, 4, 5])
3. Dictionary Comprehension
Example:
# dictionary comprehension>>> newdict = {x:x-1 for x in mylist}>>> newdict{1: 0, 2: 1, 3: 2, 4: 3}
0 0
- Python List Comprehension, Dictionary Comprehension
- python list comprehension
- [python] List Comprehension
- Python——List Comprehension
- Python中的列表推导式(list comprehension)
- python map和list comprehension 效率比较
- Python列表推导式(List comprehension)
- python:列表推导式,list comprehension
- Python中的 list comprehension 以及 generator
- Python列表推导式(List comprehension)
- python列表解释(list comprehension)记录
- List comprehension
- 11-09-15 python 列表推导List Comprehension&
- python one-line list comprehension: if-else variants
- Python map/reduce vs 列表推导式[list comprehension]
- python学习笔记——列表推导 list comprehension
- python技巧——list comprehension vs map
- Python技巧——list comprehension 与 functools.reduce
- MySQL数据库事务隔离级别(Transaction Isolation Level)
- 隐式游标的属性值变化
- 典型代码-结构与类-1
- 关于Android Studio乱码的解决办法
- 典型代码-结构与类-2
- [python] List Comprehension
- Hello,CSDN!
- mysql乐观锁总结和实践
- mysql悲观锁总结和实践
- iOS学习笔记2-NSString
- Linux环境下SVN服务器端的安装与配置
- centos minimal版本网络配置
- MFC中客户区和非客户区概念的图示
- 二维数组中的查找-自编java版本。