转自:微点阅读 https://www.weidianyuedu.com
1. 原地交换两个数字
Python 提供了一个直观的在一行代码中赋值与交换(变量值)的方法,请参见下面的示例:
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
#1 (10, 20)
#2 (20, 10)
赋值的右侧形成了一个新的元组,左侧立即解析(unpack)那个(未被引用的)元组到变量 <a> 和 <b>。
一旦赋值完成,新的元组变成了未被引用状态并且被标记为可被垃圾回收,最终也完成了变量的交换。
2. 链状比较操作符
比较操作符的聚合是另一个有时很方便的技巧:
n = 10
result = 1 < n < 20
print(result)
# True
result = 1 > n <= 9
print(result)
# False
3. 使用三元操作符来进行条件赋值
三元操作符是 if-else 语句也就是条件操作符的一个快捷方式:
[表达式为真的返回值] if [表达式] else [表达式为假的返回值]
这里给出几个你可以用来使代码紧凑简洁的例子。下面的语句是说“如果 y 是 9,给 x 赋值 10,不然赋值为 20”。如果需要的话我们也可以延长这条操作链。
x = 10 if (y == 9) else 20
同样地,我们可以对类做这种操作:
x = (classA if y == 1 else classB)(param1, param2)
在上面的例子里 classA 与 classB 是两个类,其中一个类的构造函数会被调用。
下面是另一个多个条件表达式链接起来用以计算最小值的例子:
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))
#Output
#0 #1 #2 #3
我们甚至可以在列表推导中使用三元运算符:
[m**2 if m > 10 else m**4 for m in range(50)]
#=> [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. 多行字符串
基本的方式是使用源于 C 语言的反斜杠:
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_row where row_id < 5 order by age
5. 存储列表元素到新的变量中
我们可以使用列表来初始化多个变量,在解析列表时,变量的数目不应该超过列表中的元素个数:【译者注:元素个数与列表长度应该严格相同,不然会报错】
testList = [1,2,3]
x, y, z = testList
print(x, y, z)
#-> 1 2 3
6. 打印引入模块的文件路径
如果你想知道引用到代码中模块的绝对路径,可以使用下面的技巧:
import threading
import socket
print(threading)
print(socket)
#1- <module "threading" from "/usr/lib/python2.7/threading.py">
#2- <module "socket" from "/usr/lib/python2.7/socket.py">
7. 交互环境下的 “_” 操作符
这是一个我们大多数人不知道的有用特性,在 Python 控制台,不论何时我们测试一个表达式或者调用一个方法,结果都会分配给一个临时变量: _(一个下划线)。
>>> 2 1
3
>>> _
3
>>> print _
3
“_” 是上一个执行的表达式的输出。
8. 字典/集合推导
与我们使用的列表推导相似,我们也可以使用字典/集合推导,它们使用起来简单且有效,下面是一个例子:
testDict = {i: i * i for i in xrange(10)}
testSet = {i * 2 for i in xrange(10)}
print(testSet)
print(testDict)
#set([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}
注:两个语句中只有一个 <:> 的不同,另,在 Python3 中运行上述代码时,将 <xrange> 改为 <range>。
9. 调试脚本
我们可以在 <pdb> 模块的帮助下在 Python 脚本中设置断点,下面是一个例子:
import pdb
pdb.set_trace()
我们可以在脚本中任何位置指定 <pdb.set_trace()> 并且在那里设置一个断点,相当简便。
10. 开启文件分享
Python 允许运行一个 HTTP 服务器来从根路径共享文件,下面是开启服务器的命令:
# Python 2
python -m SimpleHTTPServer
# Python 3
python3 -m http.server
上面的命令会在默认端口也就是 8000 开启一个服务器,你可以将一个自定义的端口号以最后一个参数的方式传递到上面的命令中。
11. 检查 Python 中的对象
我们可以通过调用 dir() 方法来检查 Python 中的对象,下面是一个简单的例子:
test = [1, 3, 5, 7]
print( dir(test) )
["__add__", "__class__", "__contains__", "__delattr__", "__delitem__", "__delslice__", "__doc__", "__eq__", "__format__", "__ge__", "__getattribute__", "__getitem__", "__getslice__", "__gt__", "__hash__", "__iadd__", "__imul__", "__init__", "__iter__", "__le__", "__len__", "__lt__", "__mul__", "__ne__", "__new__", "__reduce__", "__reduce_ex__", "__repr__", "__reversed__", "__rmul__", "__setattr__", "__setitem__", "__setslice__", "__sizeof__", "__str__", "__subclasshook__", "append", "count", "extend", "index", "insert", "pop", "remove", "reverse", "sort"]