Python 基礎文法(二)

來源:互聯網
上載者:User

標籤:www   排序   date   name   技術   基礎文法   括弧   count   span   

Python 基礎文法(二)

--------------------------------------------接 Python 基礎文法(一) --------------------------------------------

  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)

l1 = list(t)
print l1 #[1, 2, 3]

    元組最通常的用法是用在列印語句,如下例:

name = "Peter Zhang"
age = 25
print "Name: %s; Age: %d" % (name, age)
# Name: Peter Zhang; Age: 25

    函數如下:

    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, ve:
print "there is no 4 in tuple" # there is no 4 in tuple

   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‘}

    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

  4. 序列

    序列類型是指容器內的元素從0開始的索引順序訪問,一次可以訪問一個或者多個元素;列表、元組和字串都是序列;序列的兩個主要特點是

  索引操作符和切片操作符;索引可以得到特定元素;切片可以得到部分序列;

 1 numbers = ["zero", "one", "two", "three", "four"]
2
3 print numbers[1] # one
4 print numbers[-1] # four
5 #print numbers[5] # raise IndexError
6
7 print numbers[:] # [‘zero‘, ‘one‘, ‘two‘, ‘three‘, ‘four‘]
8 print numbers[3:] # [‘three‘, ‘four‘]
9 print numbers[:2] # [‘zero‘, ‘one‘]
10 print numbers[2:4] # [‘two‘, ‘three‘]
11 print numbers[1:-1] # [‘one‘, ‘two‘, ‘three‘]

    切片操作符中的第一個數(冒號之前)表示切片開始的位置,第二個數(冒號之後)表示切片到哪裡結束。 如果不指定第一個數,Python就從

  序列首開始。如果沒有指定第二個數,則Python會停止在序列尾。 注意,返回的序列從開始位置 開始 ,剛好在結束位置之前 結束。即開始位置是

  包含在序列切片中的,而結束位置被排斥在切片外。 可以用負數做切片。負數用在從序列尾開始計算的位置。
  5. 綁定

    當建立一個對象並給它賦一個變數的時候,這個變數僅僅“指向”那個對象,而不是表示這個對象本身! 也就是說,變數名指向電腦中儲存那個

  對象的記憶體,這被稱作名稱到對象的綁定。

    如果要複製一個列表或者類似的序列或者其他複雜的對象(不是如整數那樣的簡單對象),那麼必須使用切片操作符來取得拷貝。

---------------------------------------------- 見續 Python 基礎文法(三) ---------------------------------------------- 

Python 基礎文法(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.