参考:列表生成式www.liaoxuefeng.com
生成[1x1, 2x2, 3x3, ..., 10x10]用列表解析式怎么做?
a=[i*i for i in range(1,10)]
print (a)
#解读; a是一个列表 列表的元素是 i*i 每个i的取值由 for in 决定
结果:[1, 4, 9, 16, 25, 36, 49, 64, 81]
代码:
# utf-8
# time:2020/4/16 10:38
# author:彭张智
a = [i * i for i in range(1, 10)]
print(a)
# 解读; a是一个列表 列表的元素是 i*i 每个i的取值由 for in 决定
b = [a + b for a in '123' for b in '123']
print(b)
#两个循环实现 123 的全排列
d = {'x': 'A', 'y': 'B', 'z': 'C' }
# 字典的遍历
for k,v in d.items():
print(k,'=',v)
#将字典转换成列表
dir=[k+'='+v for k,v in d.items()]
print(dir)
L = ['Hello', 'World', 'IBM', 'Apple']
low=[s.lower() for s in L]
print(low)
#输出偶数列表
even=[n for n in range(0,10) if n%2==0]
#后面不能加else
print(even)
L1 = ['Hello', 'World', 18, 'Apple', None]
l2=[element.lower() if isinstance(element,str) else element for element in L1 ]
print(l2)