天天看点

python 几个编程技巧原地交换两个数字链状比较操作符使用三元操作符来进行条件赋值存储列表元素到新的变量中打印引入模块的文件路径交互环境下的 “_” 操作符字典/集合推导检查 Python 中的对象简化 if 语句一行代码计算任何数的阶乘找到列表中出现最频繁的数

原地交换两个数字

x, y = ,
print(x, y)
x, y = y, x
print(x, y)
           
10 20
20 10
           

链状比较操作符

n= 
result= < n< 
print(result)
result= > n<= 
print(result)
           
True
False
           

使用三元操作符来进行条件赋值

# [表达式为真的返回值] if [表达式] else [表达式为假的返回值]
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(, , ))
print(small(, , ))
print(small(, , ))
print(small(, , ))
           
0
1
2
3
           
# classA 与 classB 是两个类,其中一个类的构造函数会被调用
x = (classA if y ==  else classB)(param1, param2)
           
# 可以在列表推导中使用三元运算符
[m** if m >  else m** for m in range()]
           

存储列表元素到新的变量中

# 元素个数与列表长度应该严格相同,不然会报错
testList = [, , ]
x, y, z = testList
print(x, y, z)
           
1 2 3
           

打印引入模块的文件路径

import threading
import socket
print(threading)
print(socket)
           
<module 'threading' from '/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py'>
<module 'socket' from '/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py'>
           

交互环境下的 “_” 操作符

# 在 Python 控制台,不论何时我们测试一个表达式或者调用一个方法,结果都会分配给一个临时变量: _(一个下划线)
 + 
           
3
           
_
           
3
           

字典/集合推导

testDict= {i: i *i for i in range()}
testSet= {i *  for i in range()}
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= [, , , ]
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 [,,,]:
           

一行代码计算任何数的阶乘

# Python 2.x.
result= (lambda k: reduce(int.__mul__, range(, k+), ))()
print(result)
           
# Python 3.x.
import functools
result= (lambda k: functools.reduce(int.__mul__, range(, k+), ))()
print(result)
           
6
           

找到列表中出现最频繁的数

test= [, , , , , , , , , , ]
print(max(set(test), key=test.count))
           
4