花半個月對python3.x編程模板總結!零基礎的好好學!

剛接觸Python3版本的小夥伴們,編程時會對於Python中各種數據結構如:array、list、dict、set以及字符串str操作都不太熟悉。同時類似於Python網絡編程、文件讀取、數據庫連接以及協程這些編程模板基本也都是固定的,本文便就這些方面進行總結,希望讓大家進行Python3編程時能夠更加的便捷,可以直接複製粘貼而不用每次都手敲了,好下面進入正題啦!

私信小編01 02 03 04 即可獲取數十套PDF哦!分開私信!

花半個月對python3.x編程模板總結!零基礎的好好學!


一、list各種操作

1、list和array之間相互轉換及遍歷

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy import *
#python 中list和array之間的相互轉換以及list和array的遍歷
testList=[[1,2,3],[4,5,6]]
#將list轉化成array
testArray=array(testList)
for i in range(testArray.shape[0]):
for j in range(testArray.shape[1]):
print(testArray[i,j],' ',end='')
print()
print()
#將array轉化成list
toList=testArray.tolist()
for i in range(len(toList)):
for word in toList[i]:
print(word,' ',end='')
print()


2、查找返回list中出現次數最多的那個元素

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#查詢list中出現次數最多的元素
def top(list):
s=set(list)
d={}
for i in s:
d[i]=list.count(i)
print('下面輸出的是前k個字典:',end='')

print(d)
list1=[]
for i in d.values():
list1.append(i)
ma=max(list1)
key_max=get_keys(d,ma)
string=key_max[0]
return string
#get_keys實現已知dict的value返回key
def get_keys(d,value):
return [k for k,v in d.items() if v==value]
if __name__ == '__main__':
listTest=[1,1,1,2,2,3,4,5,5,6,6,6,6,6,7]
s=top(listTest)
print('出現次數最多的元素: ', s)


二、array各種操作

1、Python3中如何自定義結構化數組

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy import *
import pandas as pd
#通過下面這種方式定義結構數組,自定義結構數組
dtypes={'name':'s32','age':'i','weight':'f'}
mydata=pd.DataFrame([['zhang',32,65.5],['wang',24,55.2]],columns=['name','age','weight'])
print(mydata)
t=mydata.shape
for i in mydata.columns:
print('')
for j in range(mydata.ndim):
print(' '+str(mydata[i][j]),end='')


2、array切片操作

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy import *
a=arange(10)**3
for element in a.flat:
print(' %d' %element,end='')
print('')
for i in range(a.size):
print(' %d' %a[i],end='')
print('')
print(a[2:5]) #數組的切片處理
a[:6:2]=-1000 #省略的位置代表0
print(a)
m=a[: :-1] #將一維數組反轉
print(m)


三、dict各種操作

1、如何根據dict字典的value反去除key

def get_keys(d,value):
return [k for k,v in d.items() if v==value]


2、dict中存取key、value各種函數使用

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import operator
a_dict={1:{'name':'Mary'},2:'python',3:'google','email':'qq.com'}
print(a_dict)
print(a_dict.items())
#字典的三個函數 keys()、values()、items()
print(a_dict.keys())
print(a_dict.values())
print(a_dict.items())
#兩種遍歷dict中key的方式

for k in a_dict.keys():
print(k)
for k in a_dict:
print(k)
print()
#兩種遍歷dict中value的方式
for v in a_dict.values():
print(v)
for k in a_dict.keys():
print(a_dict[k])
print()
#Python字典調用items()函數以列表返回可遍歷的(鍵,值)元組數組
for k,v in a_dict.items():
print(str(k)+' : '+str(v))
for k in a_dict:
print(str(k)+' : '+str(a_dict[k]))
print()
#get函數的使用,用來取出dict的value的
for k in a_dict.keys():
print(a_dict.get(k))
print('字典的存儲的數據量為: %d' %len(a_dict))


四、set各種操作

1、set聲明操作集合和list之間轉化

import numpy as np
import operator
#set中只存儲key,不存儲value,並且key不能夠重複
#下面給出Python中聲明set的方法
s1=set([])
while len(s1)!=5:
a=np.random.randint(0,10)
s1.add(a)
print(s1)
s2=set([])
for i in range(10):

s2.add(i)
print(s2)
#兩個set進行相減操作
s3=s2-s1
print(s3)
#將set轉化成list
list1=list(s1)
list2=list(s3)
for i in range(len(list1)):
print(list1[i])
for j in range(len(list2)):
print(list2[j])


五、字符串操作

1、Python中字符串相等判斷

str1='csdn'
str2='csdn'
#Python中和Java不同,字符串相等直接使用‘==’
if str1==str2:
print('相等')
else:
print('不相等')


2、將文本中有效單詞取出,過濾掉空格和其他符號

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
#在表示完整的文件路徑需要在前面加 r
file_name = r'E:\python\Python_project\machine learning\bayes\email\ham\23.txt'
lines_count = 0
words_count = 0

chars_count = 0
words_dict = {}
lines_list = []
with open(file_name, 'r') as f:
print(f)
for line in f:
#print('line: ',line)
lines_count = lines_count + 1
chars_count = chars_count + len(line)
#這裡的findall函數特殊
match = re.findall(r'[^a-zA-Z0-9]+', line)
#print('match: ',match)
for i in match:
# 只要英文單詞,刪掉其他字符
line = line.replace(i, ' ')
#split()返回的是 list
lines_list = line.split()
#下面的i表示的是單詞,所以字典的key是單詞,value是單詞出現的次數
for i in lines_list:
if i not in words_dict:
words_dict[i] = 1
else:
words_dict[i] = words_dict[i] + 1
print('words_count is %d' %len(words_dict))
print('lines_count is %d' %lines_count)
print('chars_count is %d' %chars_count)
print(words_dict.keys())
print(words_dict.values())
for k,v in words_dict.items():
print(k,v)


六、json使用

1、Python對象和json對象相互轉化

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
#python對象--->json對象 json.dumps(python對象)

#Python對象#下面是字典類型的對象和json對象之間的互相轉化
d = dict(name='Bob', age=20, score=88)
data = json.dumps(d)
print('JSON Data is a str:', data)
reborn = json.loads(data)
print(reborn)


2、利用一個函數定製json序列化

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
#Python中類對象json對象
#利用一個函數定製json序列化
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __str__(self):
return 'Student object (%s, %s, %s)' % (self.name, self.age, self.score)
s = Student('Bob', 20, 88)
std_data = json.dumps(s, default=lambda obj: obj.__dict__)
print('Dump Student:', std_data)
rebuild = json.loads(std_data, object_hook=lambda d: Student(d['name'], d['age'], d['score']))
print(rebuild)


七、讀取文件操作

1、一次性讀取所有文件內容到內存:read()

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import datetime
#read函數對於文件過大時,會導致內存爆炸的!

with open('test1.txt','r') as f:
s=f.read()
print('open for read')
print(s)


2、每次讀取一行文件內容:readline()

l=[]
try:
f=open('test2_data.txt','r')
s=f.readline()
#每次讀取一行文件內容,循環讀取
while len(s)!=0:
list1=[]
list1=s.split('\t')
#將讀取的文件內容保存到list中
l.append(list1)
s=f.readline()
#print(l)
except:
if f:
f.close()


3、一次性讀取所有文件內容但是按行返回list:readlines() 很好用

 f=open('testSet.txt')
for line in f.readlines():
lineList=line.strip().split()
print(lineList)


4、向文件中寫信息

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import datetime
with open('test.txt', 'w') as f:
f.write('今天是 ')
f.write(datetime.now().strftime('%Y-%m-%d'))


八、數據庫操作

1、Python數據庫的連接模板

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#導入mysql驅動
import mysql.connector
#連接mysql數據庫
conn=mysql.connector.connect(user='root',password='',db='test')
cur=conn.cursor()
#查詢多條記錄
info=cur.fetchmany(5)
for ii in info:
print(ii)
#運行查詢的另一種方式
cur.execute("select * from user")
values=cur.fetchall()
print(values)
#提交事務
conn.commit()
conn.close()
cur.close()


九、TCP網絡通訊

1、服務器端server

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket,threading,time
def tcplink(socket,addr):
print('Accept new connection from %s:%s...' %addr)
sock.send(b'Welcome!')
while True:
data=sock.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8')=='exit':
break
sock.send(('Hello,%s!' % data.decode('utf-8')).encode('utf-8'))
sock.close()
print('Connection from %s:%s closed' %addr)
if __name__=='__main__':
# 創建一個socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#監聽窗口
#其中IP地址和端口號使用tuple的形式
s.bind(('127.0.0.1',9999))
#開始監聽端口
s.listen(5)
print('waiting for connection...')
#永久循環接受客服端連接
while True:
#接受一個新連接
sock,addr=s.accept()
#創建新線程處理TCP連接
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()


2、客服端client

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
# 創建一個socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#建立連接
s.connect(('127.0.0.1',9999))

#接受歡迎消息
print(s.recv(1024).decode('utf-8'))
for data in [b'Michael',b'Tracy',b'Sarah']:
s.send(data)
print(s.recv(1024).decode('utf-8'))
s.send(b'exit')
s.close()


十、Python協程async

1、Python中協程比使用多線程更高效

如是Python3.5及以上版本,代碼如下:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
async def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader,writer=await connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
await writer.drain()
while True:
line=await reader.readline()
if line== b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()


如果是Python3.4的版本,代碼如下

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = yield from connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
yield from writer.drain()
while True:
line = yield from reader.readline()
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
# Ignore the body, close the socket
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()


以上內容便是Python3.x常用數據結構和常用模板的總結,當然並不可能很全啦,後期如果有比較好的模板還會繼續更新,小夥伴們如果有比較好的模板也歡迎添加分享!


分享到:


相關文章: