1 Set 方法Python 擁有一套能夠在集合(set)上使用的內(nèi)建方法。
集合(Set) 集合是無(wú)序和無(wú)索引的集合。在 Python 中,集合用花括號(hào)編寫。 intersection() 交集 union() 并集 difference() 差集 issubset() 子集 issuperset() 父集 symmetric_difference() 對(duì)稱差集 isdisjoint() 判斷是否有差集 2 關(guān)系操作list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
?
list_2 = set([2,6,0,66,22,8,8,4])
# print(list_1,list_2)
?
# 交集
print(list_1.intersection(list_2))
?
# 并集
print(list_1.union(list_2))
?
# 差集
print(list_1.difference(list_2))
print(list_2.difference(list_1))
?
# 子集
# issubset(),返回另一個(gè)集合是否包含此集合。
# issuperset(),返回此集合是否包含另一個(gè)集合。
list_3 = set([1,3,7])
print(list_3.issubset(list_1)) # 此集合是否為另一個(gè)集合的子集合
print(list_1.issuperset(list_3)) # 此集合是否為另一個(gè)集合的父集合
?
# 對(duì)稱差集(合并沒有交集)
print(list_1.symmetric_difference(list_2))
?
?
print("---------------")
# isdisjoint()返回兩個(gè)集合是否有交集。
list_4 = set([5,6,7,8])
print(list_3.isdisjoint(list_4))
3 關(guān)系運(yùn)算符:# 交集 print(list_1 & list_2) ? # union print(list_2 | list_1) ? #difference print(list_1 - list_2) # in list_1 not in list_2 ? #對(duì)稱差集 print(list_1 ^ list_2)
4 基本操作list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
?
#添加
list_1.add("hello") #添加一項(xiàng)
list_1.update(["hi","word"]) #添加多項(xiàng),不加中括號(hào)變成'w','i', 'o', 'd', 'h', 'r'
?
#獲取長(zhǎng)度
long = len(list_1)
print(list_1,"\t",long)
?
#judge判斷
print("hello" in list_1) #判斷是否存在集合里
print("hello" not in list_1) #判斷是否不在集合里
?
#copy
list_1_copy = list_1.copy()
print(list_1,list_1_copy)
?
#delete
print(list_1.pop())
list_1.remove("haha") # 刪除不存在元素會(huì)報(bào)錯(cuò)
list_1.discard("haha") #刪除不存在元素不會(huì)報(bào)錯(cuò)
print(list_1)
?
#clear
list_1.clear()
Python 有一組可用于文件對(duì)象的方法。
read()、readline()、readlines()我們談到“文本處理”時(shí),我們通常是指處理的內(nèi)容。Python 將文本文件的內(nèi)容讀入可以操作的字符串變量非常容易。文件對(duì)象提供了三個(gè)“讀”方法: .read()、.readline() 和 .readlines()。每種方法可以接受一個(gè)變量以限制每次讀取的數(shù)據(jù)量,但它們通常不使用變量。 .read() 每次讀取整個(gè)文件,它通常用于將文件內(nèi)容放到一個(gè)字符串變量中。然而 .read() 生成文件內(nèi)容最直接的字符串表示,但對(duì)于連續(xù)的面向行的處理,它卻是不必要的,并且如果文件大于可用內(nèi)存,則不可能實(shí)現(xiàn)這種處理。
.readline() 和 .readlines() 非常相似。它們都在類似于以下的結(jié)構(gòu)中使用: Python .readlines() 示例 fh = open( 'c:\autoexec.bat') for line in fh.readlines(): print line.readline() 和 .readlines()之間的差異是后者一次讀取整個(gè)文件,象 .read()一樣。.readlines()自動(dòng)將文件內(nèi)容分析成一個(gè)行的列表,該列表可以由 Python 的 for... in ... 結(jié)構(gòu)進(jìn)行處理。另一方面,.readline()每次只讀取一行,通常比 .readlines()慢得多。僅當(dāng)沒有足夠內(nèi)存可以一次讀取整個(gè)文件時(shí),才應(yīng)該使用.readline()。 寫: writeline()是輸出后換行,下次寫會(huì)在下一行寫。write()是輸出后光標(biāo)在行末不會(huì)換行,下次寫會(huì)接著這行寫
通過readline輸出,對(duì)于比較大的文件,這種占用內(nèi)存比較小。
#coding:utf-8
f = open('poem.txt','r')
result = list()
for line in open('poem.txt'):
line = f.readline()
print line
result.append(line)
print result
f.close()
open('result-readline.txt', 'w').write('%s' % '\n'.join(result))
#coding:utf-8
'''cdays-4-exercise-6.py 文件基本操作
@note: 文件讀取寫入, 列表排序, 字符串操作
@see: 字符串各方法可參考hekp(str)或Python在線文檔http://docs./lib/string-methods.html
'''
f = open('cdays-4-test.txt', 'r') #以讀方式打開文件
result = list()
for line in f.readlines(): #依次讀取每行
line = line.strip() #去掉每行頭尾空白
if not len(line) or line.startswith('#'): #判斷是否是空行或注釋行
continue #是的話,跳過不處理
result.append(line) #保存
result.sort() #排序結(jié)果
print result
open('cdays-4-result.txt', 'w').write('%s' % '\n'.join(result)) #保存入結(jié)果文件
文件讀與寫#data = open("yesterday",'r',encoding="utf-8").read()
#r 只讀,如果連續(xù)讀兩次文件,第二次就不能讀到內(nèi)容(因?yàn)榈谝淮巫x完,光標(biāo)在最后)
"""
f = open("yesterday2",'r',encoding="utf-8")
data = f.read()
data2 = f.read()
print(data)
print("-------data2----------%s---" %data2)
"""
#w 創(chuàng)建覆蓋(原有)文件
#a = append 追加
# w,a 不能讀
?
?
f = open("yesterday2",'a',encoding="utf-8") #文件句柄
f.write("\nwhen i was young i listen to the radio\n")
data = f.read()
print('----read--------',data)
?
f.close()
文件讀與寫二f = open("yesterday",'r',encoding="utf-8")
?
count =0
for line in f:
if count == 9:
print('-------分割線-------')
count += 1
print(line)
count += 1
?
?
"""
for index,line in enumerate(f.readlnes()):
if index == 9:
print('------分割線-------')
continue
print(line.strip())
"""
?
# for i in range(5):
# print(f.readline())
文件讀與寫三1 方法f = open("yesterday",'r',encoding="utf-8") # 文件句柄
print(f.tell()) #返回當(dāng)前的文件位置。
print(f.readline())
print(f.tell())
print(f.seek(0)) #更改文件位置。
print(f.seekable()) #返回文件是否允許我們更改文件位置。
print(f.encoding) #打印文件編碼
print(f.fileno()) #從操作系統(tǒng)的角度返回表示流的數(shù)字。
#detach() #編輯過程中修改字符編碼
print(f.name)
print(f.isatty()) #返回文件流是否是交互式的。檢查文件是否已連接到終端設(shè)備:
print(f.readable()) # 是否可讀
print(f.writable()) # 是否可寫
print(f.closed) # 判斷文件是否關(guān)閉
# print(f.newlines)
f = open("yesterday",'a',encoding="utf-8") # 文件句柄
# print(f.seek(0))
f.seek(10) # 使用seek()無(wú)效
f.truncate(30)
f.close()
read()讀取剩下的所有內(nèi)容,文件大時(shí)不要用 2 打開文件模式打開文件的模式有:
"+" 表示可以同時(shí)讀寫某個(gè)文件
"U"表示在讀取時(shí),可以將 \r \n \r\n自動(dòng)轉(zhuǎn)換成 \n (與 r 或 r+ 模式同使用)
"b"表示處理二進(jìn)制文件(如:FTP發(fā)送上傳ISO鏡像文件,linux可忽略,windows處理二進(jìn)制文件時(shí)需標(biāo)注)
3 flush()刷新內(nèi)部緩沖區(qū)。 一: cmd執(zhí)行:
>d:
>python
>>> f = open("test.text","w")
>>> f.write("hello1\n")
7
>>> f.flush() # 刷新緩存區(qū)后再打開文件顯示一行內(nèi)容
>>> f.write("hello2\n")
7
>>> f.flush() # 再刷新顯示一行
二: import sys,time
for i in range(20):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)
4 r+、w+、a+# f = open("yesterday2",'r+',encoding="utf-8") # 文件句柄 讀寫
# print(f.readline())
# print(f.tell())
# num = f.tell()
# f.write("--------你好------------") #會(huì)寫在最后
# print(f.seek(num)) #寫入后光標(biāo)會(huì)跳到最后
# print(f.readline())
f = open("yesterday",'w+',encoding="utf-8") # 文件句柄 寫讀(覆蓋原文件)
# f = open("yesterday",'a+',encoding="utf-8") # 文件句柄 追加讀寫
f.write("----------hello--------\n")
f.write("----------hello--------\n")
print(f.tell())
f.seek(10)
print(f.tell())
print(f.readline())
f.write("-------------hi--------")
f.close()
5 二進(jìn)制rb、wb、abf = open("yesterday",'rb') # 文件句柄 二進(jìn)制文件
# 網(wǎng)絡(luò)傳輸用到
print(f.readline())
print(f.readline())
f = open("yesterday",'wb')
#f = open("yesterday",'ab')
f.write("--hello word--\n".encode())
f.write("--hello word--\n".encode())
文件修改1f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")
print(f.tell(),f_new.tell())
for line in f:
if "昨日當(dāng)我年少輕狂" in line:
line = line.replace("昨日當(dāng)我年少輕狂","昨日當(dāng)阿福年少輕狂")
f_new.write(line)
print(line.strip())
f.close()
f_new.close()
with為了避免打開文件后忘記關(guān)閉,可以通過管理上下文, 如此方式,當(dāng)with代碼塊執(zhí)行完畢時(shí),內(nèi)部會(huì)自動(dòng)關(guān)閉并釋放文件資源。 在Python 2.7 后,with又支持同時(shí)對(duì)多個(gè)文件的上下文進(jìn)行管理 # f = open("yesterday2","r",encoding="utf-8")
with open("yesterday2","r",encoding="utf-8") as f,open("yesterday2","r",encoding="utf-8") as f2:
for line in f:
print(line.strip())
print("-------------")
for line2 in f2:
print(line2.strip())
程序練習(xí)1 實(shí)現(xiàn)簡(jiǎn)單的shell sed替換功能import sys
find_str = sys.argv[1]
replace_str = sys.argv[2]
f = open("yesterday2","r",encoding="utf-8")
f_new = open("yesterday2.bak","w",encoding="utf-8")
print(f.tell(),f_new.tell())
for line in f:
if find_str in line:
line = line.replace(find_str,replace_str)
f_new.write(line)
f.close()
f_new.close()
2 修改haproxy配置文件用到函數(shù): arg = """{
'bakend': 'www.oldboy.org',
'record': {
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}"""
arg = eval(arg)
print(arg,type(arg))
需求: 1、查
輸入:www.oldboy.org
獲取當(dāng)前backend下的所有記錄
2、新建
輸入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}
3、刪除
輸入:
arg = {
'bakend': 'www.oldboy.org',
'record':{
'server': '100.1.7.9',
'weight': 20,
'maxconn': 30
}
}
原配置文件: eval() global
log 127.0.0.1 local2
daemon
maxconn 256
log 127.0.0.1 local2 info
defaults
log global
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
option dontlognull
listen stats :8888
stats enable
stats uri /admin
stats auth admin:1234
frontend oldboy.org
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i www.oldboy.org
use_backend www.oldboy.org if www
backend www.oldboy.org
server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
字符編碼與轉(zhuǎn)碼ASSCI英文及符號(hào)占1個(gè)字節(jié);unicode占2個(gè)字節(jié);utf-8英文字符按ASCII碼形式存儲(chǔ),中文占3個(gè)字節(jié)。 1 python2.x下:#-*- coding:utf-8 -*-
import sys
print(sys.getdefaultencoding())
s = "你好"
# utf-8 --> gbk 編碼成(需指定編碼)unicode再解碼成gbk
s_to_unicode = s.decode("utf-8")
print(s_to_unicode)
s_to_gbk = s_to_unicode.encode("gbk")
print(s_to_gbk)
# gbk --> utf-8
gbk_to_utf8 = s_to_gbk.decode("gbk").encode("utf-8")
print(gbk_to_utf8)
#輸出內(nèi)容
# assci
# 你好
# (亂碼)
# 你好
#-------------------------------------
s2 = u"你好" # 現(xiàn)在是unicode
print(s) # unicode 與 utf-8 之間可以直接打印
s_to_gbk = s.encode("gbk")
print(s_to_gbk)
# gbk --> utf-8
gbk_to_utf8 = s_to_gbk.decode("gbk").encode("utf-8")
print(gbk_to_utf8)
2 python3.x:decode:編碼成字符串 encode:解碼成對(duì)應(yīng)字符編碼的二進(jìn)制 #-*- coding:gbk -*- #這里為文件字符編碼,變量s還是unicode
s = "你好"
print(s)
s_gbk = s.encode("gbk")
print(s_gbk) #默認(rèn)就是unicode,不用decode
print(s.encode())
gbk_to_utf8 = s_gbk.decode("gbk").encode("utf-8")
print("utf-8",gbk_to_utf8)
utf8_to_gbk = gbk_to_utf8.decode("utf-8").encode("gbk")
print("gbk",utf8_to_gbk)
#--------------
print(s)
print(s.encode("gbk"))
print(s.encode("ut"))
print(s.encode("utf-8").decode("utf-8").encode("gbk2312").decode("gbk2312"))
函數(shù)與函數(shù)式編程函數(shù)
初中數(shù)學(xué)函數(shù)定義:一般的,在一個(gè)變化過程中,如果有兩個(gè)變量x和y,并且對(duì)于x的每一個(gè)確定的值,y都有唯一確定的值與其對(duì)應(yīng),那么我們就把x稱為自變量,把y稱為因變量,y是x的函數(shù)。自變量x的取值范圍叫做這個(gè)函數(shù)的定義域。如:y=2x ? 編程語(yǔ)言中函數(shù)定義:函數(shù)是邏輯結(jié)構(gòu)化和過程過得一種編程方法。 #python中函數(shù)的定義方法:
def test(x):
"The function definitions"
x += 1
return x
# def:定義函數(shù)的關(guān)鍵字
# test:函數(shù)名
# ():內(nèi)可定義形參
# "":文件描述(非必要,但是強(qiáng)烈建議為你的函數(shù)添加描述信息)
# x += 1:泛指代碼塊或程序處理邏輯
# return:定義返回值
ps:函數(shù)式編程就是:先定義一個(gè)數(shù)學(xué)函數(shù),然后按照這個(gè)數(shù)字模型用編程語(yǔ)言去實(shí)現(xiàn)它。 # 函數(shù)
def func1():
"testing1"
print('in the func1')
return 0
# 過程
def func2():
"testing2"
print('in the func2')
x=func1()
y=func2()
print(x,y)
return返回值def test1():
print("this is test1")
def test2():
print("this is test2")
return 0
def test3():
print("this is test3")
return 1,["zhangsan,lisi"],{"ar fu":"ar gui"}
t1 = test1()
t2 = test2()
t3 = test3()
print(t1)
print(t2)
print(t3)
# this is test1
# this is test2
# this is test3
# None
# 0
# (1, ['zhangsan,lisi'], {'ar fu': 'ar gui'})
1 日志加上時(shí)間import time
def logger():
time_format = '%Y-%m-%d %X'
time_current = time.strftime(time_format)
with open("yesterday","a+",encoding="utf-8") as f:
f.write("%s end action\n" %time_current)
def test1():
print("this is test1")
logger()
def test2():
print("this is test2")
logger()
test1()
test2()
概括使用函數(shù)的三大優(yōu)點(diǎn)
2 函數(shù)調(diào)用調(diào)用方法:test()執(zhí)行,()表示調(diào)用函數(shù)test,()內(nèi)可以有函數(shù)也可以沒有 參數(shù): 1.形參和實(shí)參形參:形式參數(shù),不是實(shí)際存在,是虛擬變量。在定義函數(shù)和函數(shù)體的時(shí)候使用參數(shù),目的是在函數(shù)調(diào)用時(shí)接收實(shí)參。 形參排放順序:普通形參 -->*args --> 默認(rèn)參數(shù) -->***kwargs ps:若默認(rèn)參數(shù)放在*args前,會(huì)發(fā)生默認(rèn)參數(shù)有多個(gè)值而報(bào)錯(cuò)
實(shí)參:實(shí)際參數(shù),調(diào)用函數(shù)時(shí)傳給函數(shù)的參數(shù),可以是常量,變量,表達(dá)式,函數(shù),傳給參數(shù) 區(qū)別:形參是虛擬的,不占用內(nèi)存空間,形參變量只有在被調(diào)用時(shí)才可分配內(nèi)存單元,實(shí)參是一個(gè)變量,占用內(nèi)存空間,數(shù)據(jù)傳送單向,實(shí)參傳給形參,不能形參傳給實(shí)參。 2.位置參數(shù)和關(guān)鍵字(標(biāo)準(zhǔn)調(diào)用:實(shí)參與形參位置一一對(duì)應(yīng);關(guān)鍵字調(diào)用:位置無(wú)固定)且關(guān)鍵字一定要在位置參數(shù)后面。
# 位置參數(shù)與關(guān)鍵字
def test(x,y,z): #形參
print(x)
print(y)
print(z)
# test(y=2,x=1) #關(guān)鍵字,與形參順序無(wú)關(guān)
# test(1,2) #位置參數(shù),實(shí)參與形參一一對(duì)應(yīng)
test(5,y=2,z=4) # 先位置參數(shù),再接關(guān)鍵字(到最后且不使用前面的形參)
3.默認(rèn)參數(shù)(給形參賦予一個(gè)初始值)# 默認(rèn)參數(shù)
def test(x,y=2):
print(x,y)
# print(y)
def conn(host,port=3306):
# print(host)
pass
test(1,3)
conn(1)
#默認(rèn)參數(shù)特點(diǎn):調(diào)用函數(shù)的時(shí)候,默認(rèn)參數(shù)非必須傳遞 #用途:1.默認(rèn)安裝值 2.默認(rèn)值 4.參數(shù)組def test(x,y,z=2): # 默認(rèn)參數(shù)外,實(shí)參處必須寫夠位置參數(shù)個(gè)數(shù)
print(x,y,z)
test(1,4)
*args def test(*args,age=18): #接收N個(gè)參數(shù)且轉(zhuǎn)換成元組的形式
print(args)
print(age)
test(age=12,*[1,2,3,4])
test(*[1,2,4,5,5]) #args=tuple([1,2,4,5,5])
# *args:接收N個(gè)位置參數(shù),轉(zhuǎn)換成元組形式,或*[234,234]
def test(x,*args):
print(x)
print(args)
test(1,234,234,123)
test(1,*[234,234,123])
test(1) #輸出的args為空元組
**kwargs def test2(**kwargs): # **kwargs:把N個(gè)關(guān)鍵字參數(shù)裝換成字典方式,或**{'name':'zhangsan','age':8}
print(kwargs)
print(kwargs['name'])
print(kwargs['age'])
test2(name='zhangsan',age=8,sex='N')
test2(**{'name':'zhangsan','age':8})
*args和**kwargs 形參排放順序:普通形參 --> *args --> 默認(rèn)參數(shù) -->**kwargs def test4(name,*args,age=18,**kwargs): #**kwargs(為關(guān)鍵字參數(shù))必須放最后
print(name)
print(age)
print(args)
print(kwargs)
test4('zhangsan','hello','hi',sex='m',hobby='tesla')
局部變量函數(shù)內(nèi)的變量為局部變量。global聲明可以變成全局(不建議用) musci = "最炫民族風(fēng)"
def change_name(name):
global music #函數(shù)內(nèi)聲明全局變量
music = "荷塘月色"
print("before change: ",name,music)
name = "ar fu" #這個(gè)函數(shù)就是這個(gè)變量的作用域
print("after change: ",name,music)
name = "zhang san"
change_name(name)
print(name)
print(music)
# before change: zhang san 荷塘月色
# after change: ar fu 荷塘月色
# zhang san
# 荷塘月色
函數(shù)內(nèi)可以修改的外部的數(shù)據(jù)類型 #函數(shù)內(nèi)可以修改外面全局的列表、字典、集合、類。不能改字符串和數(shù)字 school = "hello"
names = ["zhangsan","lisi","wangwu"]
def change_name():
names[0] = "趙六"
school = "hi"
print("inside func",names,school)
change_name()
print(names,school)
全局與局部變量在子程序中定義的變量稱為局部變量,在程序的一開始定義的變量稱為全局變量。 全局變量作用域是整個(gè)程序,局部變量作用域是定義該變量的子程序。 當(dāng)全局變量與局部變量同名時(shí): 在定義局部變量的子程序內(nèi),局部變量起作用,在其他地方全局變量起作用。 遞歸在函數(shù)內(nèi)部,可以調(diào)用其他函數(shù)。如果一個(gè)函數(shù)在內(nèi)部調(diào)用自身,這個(gè)函數(shù)就是遞歸函數(shù)。 遞歸特性:
def calc(n):
print(n)
if int(n/2) > 0:
return calc(int(n/2))
print("--> ",n)
calc(10)
匿名函數(shù) lambda匿名函數(shù)就是不需要顯式的指定函數(shù) def calc(n): return n**n print(calc(10)) # 換成匿名函數(shù) calc = lambda n:n**n print(calc(10))
匿名函數(shù)主要是和其他函數(shù)搭配使用 res = map(lambda x:x**2,[1,5,7,4,8])
print(type(res))
for i in res:
print(i)
<class 'map'> 1 25 49 16 64 函數(shù)式編程介紹函數(shù)是Python內(nèi)建支持的一種封裝,我們通過把大段代碼拆成函數(shù),通過一層一層的函數(shù)調(diào)用,就可以把復(fù)雜任務(wù)分解成簡(jiǎn)單的任務(wù),這種分解可以稱之為面向過程的程序設(shè)計(jì)。函數(shù)就是面向過程的程序設(shè)計(jì)的基本單元。 函數(shù)式編程中的函數(shù)這個(gè)術(shù)語(yǔ)不是指計(jì)算機(jī)中的函數(shù)(實(shí)際上是Subroutine),而是指數(shù)學(xué)中的函數(shù),即自變量的映射。也就是說(shuō)一個(gè)函數(shù)的值僅決定于函數(shù)參數(shù)的值,不依賴其他狀態(tài)。比如sqrt(x)函數(shù)計(jì)算x的平方根,只要x不變,不論什么時(shí)候調(diào)用,調(diào)用幾次,值都是不變的。
Python對(duì)函數(shù)式編程提供部分支持。由于Python允許使用變量,因此,Python不是純函數(shù)式編程語(yǔ)言。 一、定義 簡(jiǎn)單說(shuō),"函數(shù)式編程"是一種 主要思想是把運(yùn)算過程盡量寫成一系列嵌套的函數(shù)調(diào)用。舉例來(lái)說(shuō),現(xiàn)在有這樣一個(gè)數(shù)學(xué)表達(dá)式:
傳統(tǒng)的過程式編程,可能這樣寫:
函數(shù)式編程要求使用函數(shù),我們可以把運(yùn)算過程定義為不同的函數(shù),然后寫成下面這樣:
這段代碼再演進(jìn)以下,可以變成這樣
這基本就是自然語(yǔ)言的表達(dá)了。再看下面的代碼,大家應(yīng)該一眼就能明白它的意思吧:
因此,函數(shù)式編程的代碼更容易理解。 要想學(xué)好函數(shù)式編程,不要玩py,玩Erlang,Haskell, 好了,我只會(huì)這么多了。。。 高階函數(shù)變量可以指向函數(shù),函數(shù)的參數(shù)能接收變量,那么一個(gè)函數(shù)就可以接收另一個(gè)函數(shù)作為參數(shù),這種函數(shù)稱為高階函數(shù)。 def add(x,y,f):
return f(x)+f(y)
res = add(5,-10,abs) #abs:絕對(duì)值
print(res)
|
|
|