原地交换两个数字
x, y = 10,20
print(x, y)
x, y = y, x
print(x, y)
10 20
20 10
链状比较操作符
n= 10
result= 1< n< 20
print(result)
result= 1> n<= 9
print(result)
True
False
使用三元操作符来进行条件赋值
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
2
3
x = (classA if y == 1 else classB)(param1, param2)
[m**2 if m > 10 else m**4 for m in range(50)]
存储列表元素到新的变量中
testList = [1, 2, 3]
x, y, z = testList
print(x, y, z)
1 2 3
打印引入模块的文件路径
import threading
import socket
print(threading)
print(socket)
交互环境下的 “_” 操作符
2 + 1
3
_
3
字典/集合推导
testDict= {i: i *i for i in range(10)}
testSet= {i * 2 for i in range(10)}
print(testSet)
print(testDict)
{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
检查 Python 中的对象
test= [1, 3, 5, 7]
print(dir(test))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
简化 if 语句
if m in [1,3,5,7]:
一行代码计算任何数的阶乘
result= (lambda k: reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
import functools
result= (lambda k: functools.reduce(int.__mul__, range(1, k+1), 1))(3)
print(result)
6
找到列表中出现最频繁的数
test= [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key=test.count))
4