推导列表

>>> [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]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值