python 实用技巧

#原地交换两个变量
x, y = "x", "y"
print(x, y)
#('x', 'y')

x, y = y, x
print(x, y)
#('y', 'x')


#链状比较操作符
n = 1
result = 0 < n < 2
print result
#True
result = 1 > n <= 9
print result
#False

#使用三元操作符来进行条件赋值
y=11
x = 10 if (y == 9) else 20
print x
#20
#在推导式中的应用
[m**2 if m > 3 else m**4 for m in range(7)]
#[0, 1, 16, 81, 16, 25, 36]

#多行字符串用括号解决
multiStr= ("select * from multi_row "
"where row_id < 5 "
"order by age")
print multiStr
#select * from multi_row where row_id < 5 order by age

#列表初始化多个变量
x, y, z =  [4,2,3]
print x,y,z
#4 2 3

#打印引入模块的文件路径
import os
print(os)
#

#if多值验证
if m in ["x","y","z"]:
#不用 if m=="x" or m=="y" or m=="z"

你可能感兴趣的:(python 实用技巧)