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):
- returnaifa<= banda<= celse(bifb<= aandb<= celsec)
- 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]
我自己是一名高级 python 开发工程师, 这里有我自己整理了一套最新的 python 系统学习教程, 包括从基础的 python 脚本到 web 开发, 爬虫, 数据分析, 数据可视化, 机器学习等. 送给正在学习 python 的小伙伴! 这里是 python 学习者聚集地, 欢迎初学和进阶中的小伙伴!
- multiStr= "select * from multi_row
- where row_id <5"
- print(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
- testList= [1,2,3]
- x,y,z= testList
- print(x,y,z)
- #-> 1 2 3
- 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'>
- >>> 2+ 1
- 3
- >>> _
- 3
- >>> print_
- 3
- testDict= {
- i: i *iforiinxrange(10)
- }
- testSet= {
- i *2foriinxrange(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
- }
- import pdb
- pdb.set_trace()
- # Python 2
- python -m SimpleHTTPServer
- # Python 3
- python3 -m http.server
- 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']
- Python 2.x.
- result= (lambdak: reduce(int.__mul__,range(1,k+1),1))(3)
- print(result)
- #-> 6
- Python 3.x.
- import functools
- result= (lambdak: 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
- import sys
- x=1001
- print(sys.getrecursionlimit())
- sys.setrecursionlimit(x)
- print(sys.getrecursionlimit())
- #1-> 1000
- #2-> 1001
- import sys
- x=1
- print(sys.getsizeof(x))
- #-> 24
- import sys
- x=1
- print(sys.getsizeof(x))
- #-> 28
- import sys
- classFileSystem(object):
- def __init__(self,files,folders,devices):
- self.files= files
- self.folders= folders
- self.devices= devices
- print(sys.getsizeof(FileSystem))
- classFileSystem1(object):
- __slots__= ['files','folders','devices']
- def __init__(self,files,folders,devices):
- self.files= files
- self.folders= folders
- self.devices= devices
- print(sys.getsizeof(FileSystem1))
- #In Python 3.5
- #1-> 1016
- #2-> 888
- #In Python 2.7 win10
- #1-> 896
- #2-> 1016
- import sys
- lprint=lambda *args:sys.stdout.write(" ".join(map(str,args)))
- lprint("python","tips",1000,1001)
- #-> python tips 1000 1001
- t1= (1,2,3)
- t2= (10,20,30)
- print(dict(zip(t1,t2)))
- #-> {
- 1: 10, 2: 20, 3: 30
- }
- print("http://www.google.com".startswith(("http://","https://")))
- print("http://www.google.co.uk".endswith((".com",".co.uk")))
- #1-> True
- #2-> True
- import itertools
- test= [[-1,-2],[30,40],[25,35]]
- print(list(itertools.chain.from_iterable(test)))
- #-> [-1, -2, 30, 40, 25, 35]
- def xswitch(x):
- returnxswitch._system_dict.get(x,None)
- xswitch._system_dict= {
- 'files': 10,'folders': 5,'devices': 2
- }
- print(xswitch('default'))
- print(xswitch('devices'))
- #1-> None
- #2-> 2
来源: http://www.jianshu.com/p/29f0ddb53706