九、給小白看的第二篇Python基礎教程
本文是第二篇
@Author:Runsen
@公眾號:Python之王
本系列Python基礎教程共四篇,本文是第二篇。
6.2 元組
tuple和list十分相似,但是tuple是不可變的,即不能修改tuple,元組通過圓括號中用逗號分割的項定義。
- 支持索引和切片操作
- 可以使用 in查看一個元素是否在tuple中。
- 空元組()
- 只含有一個元素的元組(“a”,) #需要加個逗號
優點:tuple比list速度快;對不需要修改的數據進行『寫保護』,可以是代碼更安全
tuple與list可以相互轉換,使用內置的函數list()和tuple()。
l = [1, 2, 3]
print( l )# [1, 2, 3]
t = tuple(l)
print(t) # (1, 2, 3)
l = list(t)
print (l) #[1, 2, 3]
元組最通常的用法是用在打印語句,如下例:
name = "Runsen"
age = 20
print( "Name: %s; Age: %d") % (name, age)
# Name: Runsen; Age: 20
函數如下:
- count(value)
返回元組中值為value的元素的個數
t = (1, 2, 3, 1, 2, 3)
print (t.count(2) )# 2
- index(value, [start, [stop]])
返回列表中第一個出現的值為value的索引,如果沒有,則異常 ValueError
t = (1, 2, 3, 1, 2, 3)
print( t.index(3) )# 2
try:
print (t.index(4))
except ValueError as V:
print(V) # there is no 4 in tuple
6.3 字典
字典由鍵值對組成,鍵必須是唯一的;
eg: d = {key1:value1, key2:value2};
空字典用{}表示;字典中的鍵值對是沒有順序的,如果想要一個特定的順序,那麼使用前需要對它們排序;
d[key] = value
,如果字典中已有key
,則為其賦值為value
,否則添加新的鍵值對key/value
;
使用del d[key]
可以刪除鍵值對;判斷字典中是否有某鍵,可以使用in 或 not in;
d = {}
d["1"] = "one"
d["2"] = "two"
d["3"] = "three"
del d["3"]
for key, value in d.items():
print ("%s --> %s" % (key, value))
#1 --> one
#2 --> two
dict函數如下:
- clear()
刪除字典中所有元素
d1 = {"1":"one", "2":"two"}
d1.clear()
print (d1 )# {}
- copy()
返回字典的一個副本(淺複製)
d1 = {"1":"one", "2":"two"}
d2 = d1.copy()
print( d2 )#{'1': 'one', '2': 'two'}
print(d1 == d2) # True
print(d1 is d2) # False
淺複製值相同,但是對象不同,內存地址不同。
- dict.fromkeys(seq,val=None)
創建並返回一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值(默認為None)
l = [1, 2, 3]
t = (1, 2, 3)
d3 = {}.fromkeys(l)
print (d3) #{1: None, 2: None, 3: None}
d4 = {}.fromkeys(t, "default")
print(d4) #{1: 'default', 2: 'default', 3: 'default'}
- get(key,[default])
返回字典dict中鍵key對應值,如果字典中不存在此鍵,則返回default的值(default默認值為None)
d5 = {1:"one", 2:"two", 3:"three"}
print (d5.get(1) )#one
print (d5.get(5)) #None
print (d5.get(5, "test") )#test
- has_key(key)
判斷字典中是否有鍵key
d6 = {1:"one", 2:"two", 3:"three"}
print( d6.has_key(1) ) #True
print (d6.has_key(5)) #False
- items()
返回一個包含字典中(鍵, 值)對元組的列表
d7 = {1:"one", 2:"two", 3:"three"}
for item in d7.items():
print (item)
#(1, 'one')
#(2, 'two')
#(3, 'three')
for key, value in d7.items():
print ("%s -- %s" % (key, value))
#1 -- one
#2 -- two
#3 -- three
- keys()
返回一個包含字典中所有鍵的列表
d8 = {1:"one", 2:"two", 3:"three"}
for key in d8.keys():
print (key)
#1
#2
#3
- values()
返回一個包含字典中所有值的列表
d8 = {1:"one", 2:"two", 3:"three"}
for value in d8.values():
print( value)
#one
#two
#three
- pop(key, [default])
若字典中key鍵存在,刪除並返回dict[key],若不存在,且未給出default值,引發KeyError異常
d9 = {1:"one", 2:"two", 3:"three"}
print (d9.pop(1) )#one
print( d9) #{2: 'two', 3: 'three'}
print( d9.pop(5, None)) #None
try:
d9.pop(5) # raise KeyError
except KeyError, ke:
print ( "KeyError:", ke) #KeyError:5
- popitem()
刪除任意鍵值對,並返回該鍵值對,如果字典為空,則產生異常KeyError
d10 = {1:"one", 2:"two", 3:"three"}
print (d10.popitem() ) #(1, 'one')
print (d10) #{2: 'two', 3: 'three'}
- setdefault(key,[default])
若字典中有key,則返回vlaue值,若沒有key,則加上該key,值為default,默認None
d = {1:"one", 2:"two", 3:"three"}
print (d.setdefault(1)) #one
print (d.setdefault(5)) #None
print( d) #{1: 'one', 2: 'two', 3: 'three', 5: None}
print (d.setdefault(6, "six")) #six
print (d) #{1: 'one', 2: 'two', 3: 'three', 5: None, 6: 'six'}
- update(dict2)
把dict2的元素加入到dict中去,鍵字重複時會覆蓋dict中的鍵值
d = {1:"one", 2:"two", 3:"three"}
d2 = {1:"first", 4:"forth"}
d.update(d2)
print (d) #{1: 'first', 2: 'two', 3: 'three', 4: 'forth'}
- viewitems()
返回一個view對象,(key, value)pair的列表,類似於視圖。優點是,如果字典發生變化,view會同步發生變化。在
迭代過程中,字典不允許改變,否則會報異常
d = {1:"one", 2:"two", 3:"three"}
for key, value in d.viewitems():
print ("%s - %s" % (key, value))
#1 - one
#2 - two
#3 - three
- viewkeys()
返回一個view對象,key的列表
d = {1:"one", 2:"two", 3:"three"}
for key in d.viewkeys():
print( key)
#1
#2
#3
- viewvalues()
返回一個view對象,value的列表
d = {1:"one", 2:"two", 3:"three"}
for value in d.viewvalues():
print (value)
#one
#two
#three
6.4 序列
序列類型是指容器內的元素從0開始的索引順序訪問,一次可以訪問一個或者多個元素;列表、元組和字符串都是序列。
序列的三個主要特點是
- 索引操作符和切片操作符
- 索引可以得到特定元素
- 切片可以得到部分序列
索引操作符和切片操作符
numbers = ["zero", "one", "two", "three", "four"]
print (numbers[1] )# one
print (numbers[-1] )# four
#print( numbers[5]) # raise IndexError
print (numbers[:]) # ['zero', 'one', 'two', 'three', 'four']
print (numbers[3:]) # ['three', 'four']
print (numbers[:2]) # ['zero', 'one']
print (numbers[2:4] )# ['two', 'three']
print (numbers[1:-1] )# ['one', 'two', 'three']
切片操作符中的第一個數(冒號之前)表示切片開始的位置,第二個數(冒號之後)表示切片到哪裡結束。
如果不指定第一個數,Python就從序列首開始。如果沒有指定第二個數,則Python會停止在序列尾。
注意,返回的序列從開始位置 開始 ,剛好在結束位置之前 結束。即開始位置是包含在序列切片中的,而結束位置被排斥在切片外。 可以用負數做切片。負數用在從序列尾開始計算的位置。
本文已收錄 GitHub,傳送門~ ,裏面更有大廠面試完整考點,歡迎 Star。