1 函數(shù)定義傳參
2 模塊和包
3 標(biāo)準(zhǔn)包和第三方包和虛擬環(huán)境
4 高階函數(shù) map filter reduce
5 文件讀寫和json和pickle
1 函數(shù)的定義和實(shí)現(xiàn)
使用技巧:
設(shè)置參數(shù)默認(rèn)值 關(guān)鍵字傳參
序列傳參 字典傳參 接收序列 接收字典
返回值包含多個(gè)數(shù)據(jù)
# 函數(shù)的使用技巧-1
# 1. 為參數(shù)設(shè)置默認(rèn)值,只需要在形參后面增加 "= 具體值" 即可
def calc_exchange_rate(amt, source="CNY", target="USD"):
print(target)
if source == "CNY" and target == "USD":
# 6.7516 : 1
result = amt / 6.7516
# print(result)
print("匯率計(jì)算成功")
return result
elif source == "CNY" and target == "EUR":
result = amt / 7.7512
return result
print(calc_exchange_rate(100))
# 2. 以形參形式傳參(關(guān)鍵字傳參)
def health_check(name, age, height, weight, hr, hbp, lbp, glu):
print("您的健康狀況良好")
health_check(name="張三", height=178, age=32, weight=85.5, hr=70, hbp=120, lbp=80, glu=4.3)
# 函數(shù)的使用技巧-2
# 1. 序列傳參
def calc(a, b, c):
return (a + b) * c
l = [1, 5, 10]
print(calc(*l))
# 2. 字典傳參
def health_check(name, age, height, weight, hr, hbp, lbp, glu):
print(name)
print(height)
print(hr)
print("您的健康狀況良好")
param = {"name": "張三", "height": 178, "age": 32, "weight": 85.6, "hr": 70, "hbp": 120, "lbp": 80, "glu": 4.3}
health_check(**param)
# 3. 返回值包含多個(gè)數(shù)據(jù)
def get_detail_info():
dict1 = {
"employee" : [
{"name":"張三", "salary":1800},
{"name":"李四", "salary":2000}
],
"device" : [
{"id" : "8837120" , "title" : "XX筆記本"},
{"id" : "3839011" , "title" : "XX臺(tái)式機(jī)"}
],
"asset" :[{},{}],
"project" :[{},{}]
}
return dict1
print(get_detail_info())
d = get_detail_info()
sal = d.get("employee")[0].get("salary")
print(sal)
# 補(bǔ)充
def cheeseshop(kind, *arguments, **keywords):
print("-- Do you have any", kind, "?")
print("-- I'm sorry, we're all out of", kind)
for arg in arguments:
print(arg)
print("-" * 40)
for kw in keywords:
print(kw, ":", keywords[kw])
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch")
Result:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
2 模塊與包
導(dǎo)入
import os
當(dāng)前包 -> 內(nèi)置函數(shù) -> 環(huán)境變量
屬性
dir 列出對(duì)象的所有屬性與方法
help 查看類; 方法的幫助信息
__name__ 模塊的名稱
__file__ 文件路徑
引用
import package 只是import了init.py
from package.xx.xx import xx 引入需要的屬性和方法
from package.xx.xx import xx as rename 指定別名
from package.xx.xx import * 引入所有屬性和方法
3 標(biāo)準(zhǔn)模塊與第三方模塊
標(biāo)準(zhǔn)模塊
os:
environ system(command) sep pathsep linesep urandom(n) argv getcwd modules path platform mkdir/rmdir os.path
DateTime:
timedelta date datetime.strftime datetime.strptime time datetime.now day days
第三方模塊
Django
Flask
mysqlclient
4 自定義包的實(shí)現(xiàn)
https://chriswarrick.com/blog/2018/09/04/python-virtual-environments/
virtualenv:
pip install virtualenv; cd /home/envs; virtualenv name; activate/deactivate
pipenv
5 常用高階函數(shù)
lambda
filter, map, reduce:
filter(lambda n: n% 2 !=0, [1,2,3,4,5])
my_list = [12,3,45,6]
print(sorted(my_list, key=lambda x: x>0))
stus = [{},{}]
suts.sort(key=lambda x: x['age'])
map(function, sequence, ...)
reduce(lambda m, n: m + n, [1,2,3,4,5])
6 文件讀寫模式
'r' 'w' 'x' 'a' 'b' 't' '+'
with open("file.txt", 'r') as f:
do(f)
調(diào)整文件指針位置:file.seek(0)
read() 讀指定長(zhǎng)度內(nèi)容
readline() 讀單行
簡(jiǎn)單寫法:
>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file
readlines() 讀完放在一個(gè)list里
write() write expects a single string.
writelines() writelines expects an iterable of strings
https://stackoverflow.com/questions/12377473/python-write-versus-writelines-and-concatenated-strings
f.tell() 顯示位置
json can handle lists and dictionaries, pickle can handle complex python objects