1. 程式人生 > >python基礎教程 1-8章總結

python基礎教程 1-8章總結

python基礎教程

聲明:有些代碼是從大牛博客直接復制的,已經註明了鏈接。

1 安裝

future 特殊
u‘c:\n‘ ascii 8位 unicode 16位

2 列表和元組

‘‘.join(somelist),somelist必須是字符串序列
pop 去除列表最後一個元素 pop(0) 去除第一個
x.reverse() list(reversed(x))
y=x[:](deep copy)
list.sort(),list.sort(cmp) 在python3.x中取消了cmp參數,也不支持直接往sort()裏面傳函數了。可以構造排序函數傳遞給key來實現
numbers.sort(cmp=cmp)
#python裏方法sort()中cmp參數的用法 https://segmentfault.com/q/1010000000405289

sorted(x).reverse()
list.sort(reverse=True)
persons.sort(lambda a,b:a[‘age‘]-b[‘age‘])

後進先出
stack=[12,45,67,56,89,23,54]
def popit(num):
jieguo=[]
while True:
if len(num)==0:
break
else:
tmp=stack.pop()
jieguo.append(tmp)
print(jieguo)
popit(stack)

先進先出(fifo)的隊列(queue)
tmp=stack.pop() 換成 tmp=stack.pop(0) 或者insert(0,..)

或者collection模塊的deque對象
http://www.jb51.net/article/88139.htm
import collections
import threading
import time
candle = collections.deque(xrange(5))
def burn(direction, nextSource):
while True:
try:
next = nextSource()
except IndexError:
break
else:
print ‘%8s: %s‘ % (direction, next)
time.sleep(0.1)
print ‘%8s done‘ % direction
return
left = threading.Thread(target=burn, args=(‘Left‘, candle.popleft))
right = threading.Thread(target=burn, args=(‘Right‘, candle.pop))
left.start()
right.start()
left.join()
right.join()

http://xiaorui.cc/2014/11/02/python%E4%BD%BF%E7%94%A8deque%E5%AE%9E%E7%8E%B0%E9%AB%98%E6%80%A7%E8%83%BD%E5%8F%8C%E7%AB%AF%E9%98%9F%E5%88%97/
Deque的缺點就是remove還有判斷獲取索引的時候,速度有些慢, 因為他需要執行多遍deque相關聯的數據塊 。不像list那樣,搞一遍就行

from collections import deque
import profile,stat
import sys
import time
t0 = time.clock()
print t0
qeque=deque()
def add1(data):
qeque.append(data)
def add2():
qeque.pop()

big_n=1000000
def seq():
for i in range(big_n):
add1(i)
for i in range(big_n/2):
add2()
for i in range(big_n):
add1(i)

l=[]
def add3(data):
l.append(data)
def data4():
l.pop(-1)

def lse():
for i in range(big_n):
add3(i)
for i in range(big_n/2):
data4()
for i in range(big_n):
add3(i)

seq()
print deque
print ‘Queue‘, time.clock() - t0

3 使用字符串

使用元組
字符串格式化轉換類型

python基礎教程 1-8章總結