30个Python常用小技巧

1、原地交换两个数字
x, y =10, 20
print(x, y)
y, x = x, y
print(x, y)

10 20

20 10

2、链状比较操作符
n = 10
print(1 < n < 20)
print(1 > n <= 9)

True

False

3、使用三元操作符来实现条件赋值

[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
y = 20
x = 9 if (y == 10) else 8
print(x)

8

找abc中最小的数

def small(a, b, c):
return a if a<b and a<c else (b if b<a and b<c else c)
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))

0

1

3

3

列表推导

x = [m2 if m>10 else m4 for m in range(50)]
print(x)

[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

4、多行字符串
multistr = “select * from multi_row
where row_id < 5”
print(multistr)
select * from multi_row where row_id < 5
multistr = “”“select * from multi_row
where row_id < 5"”"
print(multistr)
select * from multi_row
where row_id < 5
multistr = (“select * from multi_row”
“where row_id < 5”
“order by age”)
print(multistr)
select * from multi_rowwhere row_id < 5order by age

5、存储列表元素到新的变量
testList = [1, 2, 3]
x, y, z = testList # 变量个数应该和列表长度严格一致
print(x, y, z)

1 2 3

6、打印引入模块的绝对路径
import threadi

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值