1、三元运算符
//简单的if else语句,可以使用三元运算符来表示,如 if 1==1: name = "wangkc" else : name = "alex" //三元表达式如下: name = wangkc if 1=1 else "alex"
2、lambda表达式:
可以接收任意多个参数并且返回单个表达式值的函数。lambda函数不能包含命令,他们所包含的表达式不能超过一个
//定义lambda表达式 my_lambda = lambda arg:arg+1 result = my_lambda(3)
3、sorted函数结合lambda
1、dict = {"name":"wkc","age":18,"city":"神州"} list = sorted(dict.items(),key =lambda i:i[0],reverse=False) //得到一个元祖列表,list =[("age",18),("city","神州"] new_dict = {} for i in list: new_dict[i[0]=i[1[]] print(new_dict) 2、li=[("a,1),("b",2),("c",3)] sorted(li,key=lambda x:x[0],reverse=False)
4、socket编程服务端和客户端
#coding:utf-8 import socket if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 8001)) sock.listen(5) while True: connection,address = sock.accept() try: connection.settimeout(5) buf = connection.recv(1024) if buf == '1': connection.send('welcome to server!') else: connection.send('please go out!') except socket.timeout: print 'time out' connection.close()
#coding:utf-8 import socket import time if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8001)) time.sleep(2) sock.send('1') print sock.recv(1024) sock.close()
5、全局解释器锁(global interpreter lock)