- 列表-----序列是Python中最基本的數據結構。序列中的每個元素都分配一個數字 - (它的位置),或索引,第一個索引是0,第二個索引是1,以此類推。
創建列表方式
- name1=[]
- name2=list()
python列表各種操作方式
#創建帶元素的列表
names=["Dave","Mark","Ann","Phil"]
print ("names=%s"% names) #打印列表所有成員
a=names[2]
print ("a=%s"%a) #打印下標爲2的元素(下標從0開始)
names[0]="Jeff" #替換下標爲0的位置的元素內容
print ("names[0]=%s" % names[0])
names.append("paula") #追加到末尾
print ("names=%s" % names)
#插入到指定位置
names.insert(2,"Thomas")
print ("names=%s" % names)
#只打印前兩個值 取值範圍爲0<=i<2 包含左不包含右
b=names[0:2]
print ("b=%s" % b)
c=names[2:] #打印從下標2開始到最後一個元素
print ("c=%s" % c)
替換從0開始到2的元素,不包括2位置,,元素多的也會順便插入再當前位置,
即0和1是Dave Mark,則2爲Jeff,之前2位置往後的元素順延至下一位
names[:2]=["Dave","Mark","Jeff"]
print ("--------names=%s" % names)
代碼執行截圖
列表高級的操作
#列表連接 d=[1,2,3]+[4,5] print ("d=%s" % d) #列表可以包含任意的Python對象 f=[1,"Dave",3.14,["Mark",7,9,[100,101]],10] #這種打印可以根據括號找對應的對象,一個括號對應列表的最外圍的括號,兩個就向內擴展一個依次。 print ("f[1] =%s"% f[1]) print ("f[3][2] =%d"% f[3][2]) print ("f[3][3][1] =%d" %f[3][3][1]) #列表高級屬性 import sys if len(sys.argv) !=2: print ("please supply a filname") raise SystemExit(1) f =open(sys.argv[1]) lines=f.readlines() f.close() fvalues=[float(line)for line in lines] print ("The minimum value is ", min(fvalues)) print ("The maximum value value is ",max(fvalues))
- 元組----Python的元組與列表類似,不同之處在於元組的元素不能修改。元組使用小括號,列表使用方括號。元組創建很簡單,只需要在括號中添加元素,並使用逗號隔開即可
#coding=utf-8 stock=("Good",100,49.10) address=('www.python.org',80) #person=(first_name,last_name,phone) #沒有圓括號python也能是元組 stock="Good",100,49.10 address='www.python.org',80 #person=first_name,last_name,phone #也可以使用數字下表來提取元組的內容 #元組和列表操作基本相同,但是元組一旦創建裏面的元素內容就不能被改變了 #案例將元組作爲對象存放近列表 filename="foo.txt" portfolio=[]#創建一個列表 for line in open(filename): fileds=line.split(",") name =fileds[0] print (" %s %s %s"% (fileds[0],fileds[1],fileds[2])) shares=int(fileds[1]) price=float(fileds[2]) stock=(name,shares,price) #創建一個元組 portfolio.append(stock) #添加元素到列表 print (portfolio)
- 集合、字典
字典是另一種可變容器模型,且可存儲任意類型對象字典的每個鍵值 key=>value 對用冒號 : 分割,每個鍵值對之間用逗號 , 分割,整個字典包括在花括號 {} 中
#coding=utf-8 #創建集合使用set()函數 集合支持標準操作,並集、交集、差集、對稱差集 s=set([3,5,9,10]) t=set("Hello") #注:集合元素是無順序的、切不能重複,不能通過數字索引找到 print ("t=%s"% t) #打印紙會打印出一個 l 因爲不會打印出重複的值 a= t | s #t和s並集 b= t & s #交集 c= t - s #差集 d= t ^ s #對稱差集 print ("a=%s b=%s c=%s d=%s"%(a,b,c,d)) # add() update() remove() t.add('x') print ('t=%s'%t) s.update([10,37,42]) print ('s=%s'% s) t.remove('H') print ('t=%s'%t)
################################
#字典 Dictionary
#字典是一個關聯數組或散列表,通過關鍵字索引對象
stock={ "name" : "GooG",
"shares" : 100,
"price" : 490.10
}
print (stock)
#插入 修改
stock["shares"]=75
stock["date"] ="June 7,2007"
print (stock)
#創建一個空字典
prices={}
prices=dict()
##字典快速查找
prices ={
"GOOG" : 490.10,
"AAPL" : 123.50,
"IBM" : 91.50,
"MSFT" : 52.13
}
print (prices)
#使用in運算符測試某個內容是不是字典成員
if 'SCOX' in prices:
p=prices['SCOX']
else:
p=0.0
print (p)
#下面也是檢測SCOX在不在字典裏面的方式。不在就給p賦值 0.0
p=prices.get('SCOX',0.0)
print (p)
#獲得字典的關鍵字列表,將字典轉爲列表即可
syms=list(prices)
print (syms) #輸出的是字典的關鍵字即 : 前面的值
#del刪除字典元素
del prices['MSFT']
print (prices)
- 迭代器----迭代和循環是Python中很重要的
#coding=utf-8
#迭代和循環是Python中很重要的
for n in [1,2,3,4,5,6]:
print ("2 to the %d power is %d" % (n,2**n))
print (n)
for n in range(1,10):
print ("2 to the %d power is %d" % (n,2**n))
#range(i,j,k) 表示創建的從i到j-1的以k值遞進的整數值
a=range(0,10,2)
print (a)
b=range(0,10)
print (b)
c=range(10)
print (c)
d=range(10,1,-1)
print (d)
#處理字符串
e='hello world'
for f in a:
print (f)
h=["Dave","Mark","Ann","Phil"]
for name in h:
print (name)
i={'GOOG':490.10,'IBM': 91.50,'AAPl':123.15}
for key in i:
print (key,i[key])
f=open('foo.txt')
for line in f:
print (line)
- 生成器---在Python中,一邊循環一邊計算的機制,稱爲生成器
#coding=utf-8
#使用yield 可以使函數生成一個結果序列
def countdown(n):
print ("Counting down")
while n>0:
yield n
n-=1
c=countdown(5)
for n in range(0,5):
print ("c.next()=%d"% next(c)) #3.x後生成器的下一個需要next(C) 2.X版本是 C.next()
#一般調用Yield生成器生成的函數會使用循環
for i in countdown(5):
print (i)
#生成器是基於處理管道、數據流的一種更強大的編碼方式
#1.監控日誌文件的 UNIX tail -f命令
import time
def tail(f):
f.seek(0,2)
while True:
line=f.readline()
if not line:
time.sleep(0,1)
continue
yield line
#2.使用生成器在多行中查找特定字符處啊
def grep(lines,searchtext):
for line in lines:
if searchtext in line:
yield line
#合併1、2創建一個簡單的管道
#UNIX "tail -f | grep python python " 命令的python實現
#wwlog=tail(open("access-log"))
#pylines=grep(wwwlog,"python")
#for line in pylines:
# print line
#協程
#####函數在使用時要輸入一組參數,可以將函數編寫爲一個任務,從而能處理髮送給他的一系列輸入,該類函數稱爲協程使用Yield語句可以創建協程
def print_maches(matchtext):
print ("Looking for",matchtext)
while True:
line=(yield) #獲得一行文本
if matchtext in line:
print (line)
matcher=print_maches("python")
next(matcher) #向前執行第一條(Yield)語句
matcher.send("Hello World")
matcher.send("python is cool")
matcher.close() #匹配器函數調用結束
#基於生產者-消費者模型編寫併發程序,協程很有用。 共同使用生成器和協程的例子如下
#一組匹配器協程
matchers=[print_maches("python"),print_maches("guido"),print_maches("jython")]
#通過調用next()準備所有的匹配器
for m in matchers:
next(m)
#爲所有匹配器提供一個活動日誌文件,必須有一臺活動的web服務器將數據寫入
wwwlog=tail(open("access-log"))
for line in wwwlog:
for m in matchers:
m.send(line) #將數據發送到每個匹配器協程中
- 字符串
#coding=utf-8
a= 'hello world'
b="Python is groovy"
c=""" Computer says No """
print (''' Content-type: text/html
<h1> Hello <h1>
Click <A href="http://www.python.org">here</a>
''')
#切片運算符 s[i:j] 提取字符串中索引 K 處的字符 i<=k<j
#省略i 則從字符串起始位置s[:j] 0 <= k<j
d=a[:5]
e=a[:6]
f=a[3:8]
print ("d=%s e=%s f=%s" % (d ,e ,f))
# +連接兩個字符串
d= d+e
print ("d=%s" % d)
#執行數學運算 只能轉數字字符串
z=int("23")+int("23")
print ("z=%d"% z)
- 條件判斷
#coding=utf-8 a=1;b=2; if a<b: print ("computer say yes") else: print ("computer say no") product ="game"; type="pirate memory"; age =5; if product == "game" and type == "pirate memory" \ and not (age < 4 or age >8): print ("I'll take it") #python not have switch case suffix= ".jpg" if suffix == ".htm": content="text/html" elif suffix == ".jpg": content="image/jpeg" elif suffix == ".png": content="image/png" else: raise RuntimeReeor("Unknown content type") print ("content =%s" % content) #if 條件語句如果要表示爲空的話可以使用pass語句 if a: pass else: pass
- 異常
#coding=utf-8 #使用def 創建函數 def remainder(a,b): q=a//b #截斷除法運算符 r=a-q*b return r #調用函數只需result=remainder(31,15) #要讓函數返回多個值,可以使用元組(...) def divide(a,b): q=a//b print ("q=%d"% q) r=a-q*b print ("r=%d"% r) return (q,r) #使用元組返回多個值時,可以容易的江邊來那個放到單獨的變量中 quot,remd=divide(1456,33) print (quot,remd) #給函數參數提供一個默認值 調用時可以省略該參數 #def connect(hostnaem,port,timeout=300): #函數體 # connect("www.python.org",80) #也可以使用函數參數名稱去任意順序填寫參數,前提得知道函數的參數名稱 # connect(port=80,hostname="www.python.org",timeout=30) #在函數內部修改某個全局變量的名稱使用global count=0 def foo(): global count count += 1 print ("count=%d"%count) foo() print ("count=%d"%count)
- 異常
#coding=utf-8 #如果程序中出現異常,就會引發一系列的錯誤 使用try catch語句可以追蹤並處理異常 try: f=open("file.txt","r") except IOError as e: print (e) #上述中如果出現異常會將錯誤信息放置在對象e中然後將控制權傳遞給except代碼塊 #python中的模塊 #在python中 隨着代碼的越來越多,爲了便於維護需要分爲多個文件 然後在其他文件或者腳本中導入使用 #在其他文件中使用某個模塊可以這樣 import filename 例: # 模塊文件div.py def divide(a,b): q=a/b r=a-q*b return (q,r) #在另一個文件中使用 import div a,b=div.divide(2,3) #使用不同的名稱導入到當前文件 可以使用as限定符 import div as foo a,b=foo.divide(2,3) #要將具體的定義導入到當前的命名空間中可以使用from 如果要將divide函數導入另一個文件 from div import divide a,b=divide(2,3) #導入所有的模塊到另一個文件中 from div import *
- 文件輸入輸出
# -*- coding: UTF-8 -*- f=open("foo.txt") line=f.readline() while line: print line, line=f.readline() f.close() for line in open("foo.txt"): print line, #重定向輸出打印到out文件中,類似於打印log #redirect print to a out file,likes print log to fle year =1; principal=1;numyears=5;rate=0.2 f=open("out","w") while year <= numyears: principal = principal *(1+rate) print >> f,"%3d %0.2f " % (year,principal) #python 2 f.write("%3d %0.2f \n" % (year,principal)) #也是將內容寫入文件 #print("%3d %0.2f" % (year,principal),file=f) #python 3 year+=1 f.close() #標準文件輸入輸出 import sys sys.stdout.write("Enter your name:") name=sys.stdin.readline() #在python 2 中上述輸入等價於--->name1=raw_input("Enter your name:") #在python 3 中上述輸入等價於--->name2=input("Enter your name:")