>>> [x+1 for x in range(1,10,2)]
[2, 4, 6, 8, 10]
>>> [x+10 for x in range(1,10,2)]
[11, 13, 15, 17, 19]
>>> [x*y for x in range(1,10,2) for y in range(3)]
[0, 1, 2, 0, 3, 6, 0, 5, 10, 0, 7, 14, 0, 9, 18]
>>> [x*y for x in range(1,10,2) for y in range(3) if x==1]
[0, 1, 2]
>>> d={"a":"b",1:2,"c":"d"}
>>> [str(k)+"="+str(v) for k,v in d.items()]
['a=b', '1=2', 'c=d'] #遍历字典
把一个字符串里的所有字母变成大写,用推导列表实现
#转大写的两种方法:
>>> "a".upper()
'A'
>>> chr(ord("a")-32)
'A'
方法一:
>>> s="i am a boy"
>>> "".join([i.upper() for i in s])
'I AM A BOY'
方法二:
>>> s="i am a boy"
>>> "".join([chr(ord(i)-32) for i in s if i>="a" and i<="z"])
'IAMABOY'
矩阵转置(行列数值交换),用推导列表
#for i in a 取出每一行
>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> [[j[i] for j in a] for i in range(3)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
理解:
i=0 j[0]--->[1,4,7]
i=1 j[1]--->[2,5,7]
i=2 j[2]--->[7,8,9]
>>> [j[0] for j in a]
[1, 4, 7]
>>> [j[1] for j in a]
[2, 5, 8]
>>> [j[2] for j in a]
[3, 6, 9]
删除二维列表的第一列
>>> a=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
>>> [[i[j] for j in range(3)] for i in a]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> [[i[j] for j in [1,2]] for i in a] #删除第一列
[[2, 3], [5, 6], [8, 9], [11, 12]]
>>> [[i[j] for j in [0,2]] for i in a] #删除第二列
[[1, 3], [4, 6], [7, 9], [10, 12]]