python基礎教程 1-8章總結

來源:互聯網
上載者:User

標籤: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章總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.