原創:叫我詹躲躲
來源:思否
鏈接:https://segmentfault.com/a/11...
1.輸出 %佔位符
lastname = 'hello'
firstname = 'world'
print('我的名字是%s %s' %(lastname,firstname))
2.常用的格式化字符
%c 字符
%s 通過str來格式化
%i 有符號十進制整數
%d 有符號十進制整數
%u 無符號十進制整數
%o 八進制整數
%x 十六進制整數(小寫字母)
%e 索引符號(小寫e)
%E 索引符號(大寫E)
%f 浮點實數
%g %f和%e的簡寫
%G %f和%E的簡寫
3 格式化的其他方式 format
name = '老夫子'
age = 28
print('姓名:{},年齡{}'.format(name,age))
姓名:老夫子,年齡28
4.匿名函數
lambda 參數1,參數2,參數3:表達式
特點:
1.使用lambda關鍵字創建函數
2.沒有名字的函數
3.匿名函數冒號後面的表達式有且只有一個,是表達式不是語句
4.自帶return
5.lambda 示例1
def computer(x,y):
# 計算兩數和
return x+y
M = lambda x,y:x+y
print(M(1,2))
6.lambda 示例1
result = lambda a,b,c:a*b*c
print(result(12,121,1))
7 lambda 三元表達式模擬
age = 15
print('可以參軍' if age>18 else '繼續上學')
# 直接調用
result = (lambda x,y:x if x>y else y)(2,5)
8.遞歸函數
# 階乘函數
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
pass
print(factorial(3))
9 遞歸案例 模擬實現 樹形結構的遍歷
import os #文件操作模塊
def findFile(file_path):
listRs = os.listdir(file_path) #得到該路徑所有的文件夾
for fileItem in listRs:
full_path = os.path.join(file_path,fileItem)
if os.path.isdir(full_path): #判斷是否為文件夾
findFile(full_path)
else:
print(fileItem)
pass
pass
else:
return
findFile('F:\\7.代碼學習')
10.python的內置函數
abs(-27) #絕對值
round(21.1123) #浮點近似值
pow(2,3) #冪 2**3
divmod(10,3) # 商餘
max(1,2,3,4) #最大值
min(1,2,3,4) #最小值
sum(1,2,3,4) #求和
eval() #動態執行表達式
11.類型轉換函數
int #整型
float #浮點型
str #字符類型
ord #返回對應字符的ASCII
chr # 數字轉字符 ASCII
bool # boolean
bin # 轉換二進制
hex #轉換為十六進制
oct # 八進制
list #元祖轉列表
tuple #元祖
dict #創建字典
bytes #轉為字節
12.可迭代參數 all
# all 用於判定給定的可迭代參數中的所有元素是否都為TRUE,如果是返回TRUE,否則返回FALSE,除了0,空,False 外都算TRUE
def all(iterable):
for ele in iterable:
if not ele:
return False
return True
li = [1,2,3,4,5,6,False]
print(all(li)) #False
12 可迭代參數 any
# 全部為false,返回false
def any(iterable):
for ele in iterable:
if ele:
return False
return True
li = [0,False,'']
print(any(li)) #False
13.enumerate 列出遍歷數據和下標
li = ['a','b','c']
for index,item in enumerate(li,7):
print(index,item)
# 改下標
7 a
8 b
9 c
14.set集合 不支持索引和切片,無序不重複
1.創建集合1
set1 = {'1','2'}
set2 = {'11','1'}
# 添加 add
set1.add('3')
# 清空 clear()
set1.clear()
# 取差集 difference
set1.difference(set2) #set1取set1中有的
# 取交集
set1.intersection(set2)
# 取並集
set1.union(set2)
set1 | set2
# 末尾移除
set1.pop()
# 指定移除
set1.discard(3)
# 更新 update 合併一起去重
set1.update(set2)
15 練習題1 三組數據求和
# 1-10,20-30,35-40
def threeSum(a1,a2,a3):
return sum(a1+a2+a3)
a1 = list(range(1,11))
a2 = list(range(20,31))
a3 = list(range(35,41))
print(threeSum(a1,a2,a3))
16 練習題2 大小和尚多少個
def computers():
for i in range(1,101):
for j in range(1,34):
if i+j==100 and 3*j+i/3 ==100:
print('大和尚有{}個,小和尚有{}個'.format(j,i))
pass
computers()
# 大和尚有25個,小和尚有75個
17 練習題3 找出獨一無二的數據
li = [1,1,1,2,2,2,2,3,2,2,3,4,2,1,1]
def findUnionNumber(li):
for item in li:
if li.count(item)==1:
return item
pass
print(findUnionNumber(li))
1.字典統計每個元素的次數
dict ={}
for key in li:
dict[key] = dict.get(key,0)+1
print(dict)
2.collection包下Counter類統計
from collections import Counter
a = [1, 2, 3, 1, 1, 2]
result = Counter(a)
print(result)
3.pandas包下的value_counts方法統計
import pandas as pd
a = pd.DataFrame([[1,2,3],
[3,1,3],
[1,2,1]])
result = a.apply(pd.value_counts)
print(result)
18.利用set找出獨一無二的數據
li = [1,2,3,3,2,3,4,4,5,1,2,1]
def uniqueNum(li):
set1 = set(li)
for i in set1:
li.remove(i)
set2 = set(li)
for j in set2:
set1.remove(j)
return set1
print(uniqueNum(li))
19 面向對象編程 oop
# 面向過程編程 根據業務從上到下開始編程
# 類的結構
# 類名 屬性 方法
class People:
name = 'zhan',
age = 20,
def eat(self):
print('正在吃飯')
# 創建對象
people = People()
people.eat()
20 在類的內部,使用def定義的為實例方法,第一個參數為self,實例方法歸實例所有
21 添加實例屬性
class People:
name = 'zhan',
age = 20,
def eat(self):
print('正在吃飯')
# 創建對象
people = People()
people.eat()
# 添加屬性
people.name2 = 'zhan'
people.age2 = 22
22. 類的__init__()方法
class People:
# 初始化的操作,實例屬性,自動執行
def __init__(self):
self.name = 'zhan'
self.age = 20
def eat(self):
print('正在吃飯')
# 創建對象
people = People()
people.eat()
23. 類的__init__()使用參數
class People:
# 初始化的操作,實例屬性,自動執行
def __init__(self, name, age):
self.name = name
self.age = age
def eat(self,food):
print(self.name+food)
# 創建對象
people = People('叫我詹躲躲', 20)
people.eat('正在吃飯')
people.eat('洗澡')
people.eat('跑步')
24 理解類的self
# 類似於js裏面的this
class Person:
def eat(self):
print(id(self))
pass
pass
person = Person()
person.eat()
print(id(person))
# self和對象指向同一個內存地址,self就是對象的引用
#<__main__.Person object at 0x0000020864815CC0>
25 魔術方法
__init__ :初始化實例屬性
__str__ :自定義對象的格式
__new__ :對象實例化
__class__
__del__
class Animal:
def __str__(self):
return '3213213123123'
pass
pass
animal = Animal()
print(animal)
class Animal:
def __str__(self):
return '3213213123123'
pass
pass
def __new__(cls,*args,**kwargs):
print("----new執行---")
return object.__new__(cls) #真正創建對象實例的
pass
animal = Animal()
print(animal)
# __new__ 和__init__的區別
__new__ 類的實例化方法,必須返回實例,否則創建不成功
__init__數據屬性的初始化工作,認為是實例的構造方法,接受實例化self並對其進行構造
__new__ 至少一個參數是cls,代表要實例化的類
__new__ 執行要比__init__早
26 案例練習 決戰紫禁之巔
# 屬性:
# name:玩家名稱
# blood:血量
# 方法:
# tong() 捅一刀,掉10滴血
# kanren() 砍一刀掉15滴血
# chiyao() 補血10滴血
# __str__打印玩家的狀態
class Role:
def __init__(self,name,blood):
self.name = name
self.blood = blood
pass
# 砍人
def tong(self,enemy):
enemy.blood -=10
info = '【%s】捅了【%s】一刀'%(self.name,enemy.name)
print(info)
pass
# 砍人
def kanren(self,enemy):
enemy.blood -=15
info = '【%s】砍了【%s】一刀'%(self.name,enemy.name)
print(info)
pass
# 吃藥
def chiyao(self):
self.blood +=10
info = '【%s】吃了一口藥,增加10滴血'%(self.name)
print(info)
pass
def __str__(self):
return '%s還剩下%s的血量'%(self.name,self.blood)
xmcx = Role('西門吹雪',100)
ygc = Role('葉孤城',100)
while True:
if xmcx.blood<=0 or ygc.blood<=0:
break
print('*********************')
xmcx.tong(ygc)
xmcx.kanren(ygc)
print('*********************')
ygc.tong(xmcx)
ygc.chiyao()
print('*********************')
print(xmcx)
print(ygc)
*********************
【西門吹雪】捅了【葉孤城】一刀
【西門吹雪】砍了【葉孤城】一刀
*********************
【葉孤城】捅了【西門吹雪】一刀
【葉孤城】吃了一口藥,增加10滴血
*********************
西門吹雪還剩下50的血量
葉孤城還剩下25的血量
*********************
【西門吹雪】捅了【葉孤城】一刀
【西門吹雪】砍了【葉孤城】一刀
*********************
【葉孤城】捅了【西門吹雪】一刀
【葉孤城】吃了一口藥,增加10滴血
*********************
西門吹雪還剩下40的血量
葉孤城還剩下10的血量
*********************
【西門吹雪】捅了【葉孤城】一刀
【西門吹雪】砍了【葉孤城】一刀
*********************
【葉孤城】捅了【西門吹雪】一刀
【葉孤城】吃了一口藥,增加10滴血
*********************
西門吹雪還剩下30的血量
葉孤城還剩下-5的血量
27 實例練習1 水果類
class Fruit:
def __init__(self,name,color):
self.name = name
self.color = color
def showColor(self):
print('%s的顏色為%s'%(self.name,self.color))
apple = Fruit('蘋果','紅色').showColor()
orange = Fruit('橘子','黃色').showColor()
watermelen = Fruit('西瓜','綠色').showColor()
28 驗證self 就是實例本身
class CkeckSelf:
def __str__(self):
print(id(self))
pass
CkeckSelf().__str__()
selfObj = CkeckSelf()
print(id(selfObj))
29 定義animal類,輸出所有的屬性
class Animal:
def __init__(self, color, name, age):
self.color = color
self.name = name
self.age = age
def run(self):
print('%s在跑步'%(self.name))
pass
def eat(self):
print('%s在吃東西' %(self.name))
pass
def __str__(self):
return '%s歲的%s的%s'%(self.age,self.color,self.name)
cat = Animal('黑色','小貓',2)
dog = Animal('白色','小狗',3)
cat.run()
dog.run()
print(cat)
print(dog)
# 小貓在跑步
# 小狗在跑步
# 2歲的黑色的小貓
# 3歲的白色的小狗
原創:叫我詹躲躲
來源:思否
鏈接:https://segmentfault.com/a/11...