reduce():對於序列內全部元素進行累計操做python
import _functools li=(1,2,3,4,5,6,7); def add(a,b): return a+b; total=_functools.reduce(add,li); print(total);
import _functools li=(1,2,3,4,5,6,7); def add(a,b): return a+b; total=_functools.reduce(add,li,100);#初始值爲100 print(total);
sorted()可對list進行排序:app
ol=[1,5,3,7,9,33,45,10]; ul=sorted(ol); print(ul);
ol=[True,False]; ul=sorted(ol); print(ul);
reversed_cmp函數:函數
ol=[1,5,3,7,9,33,45,10]; ul=sorted(ol,reverse=True);#默認正序爲False print(ul);
ol=[('Bob',74),('Adam',92),('Bart',66),('List',88),('aisa',88)]; print(ol); ol=sorted(ol,key=lambda s:str(s[0]).lower(),reverse=False); print(ol);
小練習:orm
# usr/bin/python # -*-coding:utf-8-*- flag = True; names = ['ok', 'ko']; phones = ['232323232', '12312332']; def Menu(): global flag while flag: print("\n\n=======通信錄管理系統=======") print("1.增長姓名和手機") print("2.刪除姓名") print("3.修改手機") print("4.查詢全部用戶") print("5.根據姓名查找手機號") print("6.退出") print("============================") i = int(input("請選擇:")); while True: if i in range(1, 7): break; else: i = int(input("輸入錯誤,請從新輸入!")) if i == 1: addUser(); elif i == 2: delUser(); elif i == 3: updatePhone(); elif i == 4: showList(); elif i == 5: getPhoneByName() elif i == 6: flag = False; def addUser(): name=input('請輸入姓名:') if checkUser(name)!=-1: print("姓名已存在!") else: names.append(name); phones.append(input('請輸入手機號:')); def delUser(): name = input("請輸入姓名:"); index=checkUser(name) if index!=-1: names.pop(index); phones.pop(index); print("刪除成功!") else: print("姓名不存在!") def updatePhone(): phone = input("請輸入手機號:"); index=checkPhone(phone); if index!=-1: new_phone = input("請輸入新的手機號:"); phones[index] = new_phone print("修改爲功!") else: print("手機號不存在!") def showList(): for i in range(len(names)): print(names[i], phones[i]) def getPhoneByName(): name = input("請輸入姓名:"); index=checkUser(name) if index!=-1: print("手機號:", phones[index]) else: print("姓名不存在!") def checkPhone(phone): if phone in phones: return phones.index(phone) else: return -1; def checkUser(name): ''' :param name 查找的名字: :return 有:下標 沒有-1: ''' if name in names: return names.index(name) else: return -1; Menu();
類和對象對象
class Student:#類的命名不能使用除下劃線之外的其餘字符,不能以數字開頭 pass#用於保證合適完整,保證語義完整
class Student: def __init__(self,name,age): self.name=name; self.age=age; def showName(self): print("我叫{}".format(self.name)); zhangsan=Student('張三',30); zhangsan.showName()
class Student: def showName(self): print("我叫{}".format(self.name)); zhangsan=Student(); zhangsan.name='張三'; zhangsan.showName()
class Student: def showName(self): print("我叫{}".format(self.name)); zhangsan=Student(); zhangsan.name='張三'; zhangsan.name='ok';#第二個值會覆蓋第一個值 zhangsan.showName()