python 高级特性:List Comprehensions(列表生成式)
2018-07-16 15:01
288 查看
列表生成式: 创建List
格式:
新列表 = [表达式/函数 for 变量 in 旧列表]
一、普通创建List
#!/usr/bin/python
#common establish way
lis1 = [];
for x in range(1, 10):
lis1.append(x);
print "lis1:", lis1;
二、列表生成式
#List comprehensions
lis2 = [x for x in range(1, 10)]
print "lis2:", lis2;
#also can choose the even number in list
lis3 = [x * x for x in range(1, 10) if x%2 == 0]
print "lis3:", lis3;
#two for in list
lis4 = [x + y for x in 'ABC' for y in 'XYZ']
print "lis4:", lis4;
#show the file in directory
import os; #导入OS模块
lis5 = [d for d in os.listdir('.')]
print lis5;
#convert all big_write string to small_write
L = ['ABC', 'EFG', 'Hij', '8'] #只能为char类型,其他类型提示出错
lis6 = [s.lower() for s in L] #lower()是内置函数,将大写转为小写
print lis6;
格式:
新列表 = [表达式/函数 for 变量 in 旧列表]
一、普通创建List
#!/usr/bin/python
#common establish way
lis1 = [];
for x in range(1, 10):
lis1.append(x);
print "lis1:", lis1;
二、列表生成式
#List comprehensions
lis2 = [x for x in range(1, 10)]
print "lis2:", lis2;
#also can choose the even number in list
lis3 = [x * x for x in range(1, 10) if x%2 == 0]
print "lis3:", lis3;
#two for in list
lis4 = [x + y for x in 'ABC' for y in 'XYZ']
print "lis4:", lis4;
#show the file in directory
import os; #导入OS模块
lis5 = [d for d in os.listdir('.')]
print lis5;
#convert all big_write string to small_write
L = ['ABC', 'EFG', 'Hij', '8'] #只能为char类型,其他类型提示出错
lis6 = [s.lower() for s in L] #lower()是内置函数,将大写转为小写
print lis6;
相关文章推荐
- Python自学笔记之高级特性2——列表生成式
- Python3 学习笔记16_高级特性(列表生成式)_20180307
- python2.7学习笔记(6) ——高级特性:切片、迭代、列表生成式、生成器
- Python 高级特性之列表生成式
- Python3 基础:高级特性-列表生成式和生成器
- Python高级特性(切片 迭代 列表生成式 生成器 迭代器)学习笔记
- python的高级特性:切片,迭代,列表生成式,生成器,迭代器
- 【Python学习笔记】python高级特性:列表生成式
- Python高级特性(切片,迭代,列表生成式,生成器,迭代器)
- Python 高级特性之列表生成式
- Python之高级特性(切片,迭代,列表生成式,生成器)
- python切片、迭代、生成器、列表生成式等高级特性学习
- Python高级特性(切片,迭代,列表生成式、生成器、迭代器)
- Python学习札记(十七) 高级特性3 列表生成式
- Python高级特性:列表生成式
- python高级特性(3):列表生成式
- 【Python】[高级特性]切片,迭代,列表生成式,生成器,迭代器
- 转载:Python高级特性 列表生成式(List Comprehensions)
- Python高级特性-迭代(Iteration)-列表生成式-生成器
- Python的高级特性之切片、迭代、列表生成式、生成器