Python中的可變類型與不可變類型

1.列表操作

1.賦值  
>>>ll = ['2', 'hello', 8.9, ['hahhah', 2]]
>>> list_from_other = list('Hello Wrold!')
>>> list_from_other
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'r', 'o', 'l', 'd', '!']

2.訪問
>>> ll[0]
'2'
>>> ll[3]
['hahhah', 2]
>>> ll[3][0]
'hahhah'
>>> ll[-3:-1]
['hello', 8.9]

3.更新
>>> ll[0]=1234567890
>>> ll
[1234567890, 'hello', 8.9, ['hahhah', 2]]
>>> ll.append('This is a test!')
>>> ll
[1234567890, 'hello', 8.9, ['hahhah', 2], 'This is a test!']
>>> l = ['string', 's', 56]
>>> ll.extend(l)
>>> ll
[1234567890, 'hello', 8.9, ['hahhah', 2], 'This is a test!', 'string', 's', 56]

4.刪除
>>> del ll[1]
>>> ll
[1234567890, 8.9, ['hahhah', 2], 'This is a test!', 'string', 's', 56]
>>> ll.remove('This is a test!')
>>> ll
[1234567890, 8.9, ['hahhah', 2], 'string', 's', 56]
>>> ll.pop(2)
['hahhah', 2]
>>> ll
[1234567890, 8.9, 'string', 's', 56]
>>> ll.pop()
56

2.序列類型可用的內建函數(shù)

>>> alist = [100, 3, 0, 34, 98, 33, 0.3, 54, 23]

1.迭代
>>> for item in alist:  #遍歷元素
        print item

    
100
3
0
34
98
33
0.3
54
>>> for i in range(len(alist)):   #對每個元素進行操作
        alist[i] * 2

    
200
6
0
68
196
66
0.6
108

>>> for index, value in enumerate(alist): #同時返回index和list中的元素
        print index, value

    
0 100
1 3
2 0
3 34
4 98
5 33
6 0.3
7 54
8 23

>>> for i, j in zip(ll, l): #zip()參數(shù)可以是dict或tuple,同時輸出多個,以最短的為主
        print i, j

    
1234567890 string
8.9 s
string 56

2.len()返回List長度
>>> print len(alist)    
9

3.返回List中最大的元素
>>> max(alist)   
100

4.返回List中最小的元素
>>> min(alist)   
0

5.返回List中元素的和盾碗,只有List全部是數(shù)字才可以
>>> sum(alist)    
345.3

6.sorted()方法返回排序號的序列,有字母時按照ASCⅡ碼排序
>>> print sorted(alist)    
[0, 0.3, 3, 23, 33, 34, 54, 98, 100]

7.reversed()方法不返回序列锰镀,返回一個迭代器
>>> print reversed(alist)
<listreverseiterator object at 0x0000000002053B38>
>>> alist
[100, 3, 0, 34, 98, 33, 0.3, 54, 23]

3.序列操作符

>>> alist = [100, 3, 0, 34, 98, 33, 0.3, 54, 23]

1.成員判斷符,'in'或者'not in '
>>> 100 in alist
True
>>> 2 in alist
False
>>> 0  not in alist
False

2.切片'[::]'或者'[:]'  slice[n:m]開始的位置包括n,結束在m之前织中,類似左開右閉區(qū)間 [n,m)
>>> alist[::2]
[100, 0, 98, 0.3, 23]
>>> alist[2:5:2]
[0, 98]
>>> alist[::-1]
[23, 54, 0.3, 33, 98, 34, 0, 3, 100]

3.重復操作符'*'  
>>> ll = ['2', 'hello', 8.9, ['hahhah', 2]]
>>> list1 = ll * 2
>>> list1
['2', 'hello', 8.9, ['hahhah', 2], '2', 'hello', 8.9, ['hahhah', 2]]

4.連接操作符'+'  
>>> list2 = alist + ll
>>> list2
[100, 3, 0, 34, 98, 33, 0.3, 54, 23, '2', 'hello', 8.9, ['hahhah', 2]]

4.列表類型內建函數(shù)


list.append(obj)
list.extend(seq)
list.remove(obj)
list.pop([index=-1])

list.count(obj)返回一個obj在List中出現(xiàn)的次數(shù)
>>> test_list
[100, 3, 0, 34, 98, 33, 0.3, 54, 23, 3, 1234567890, 8.9, 'string', 's']
>>> test_list.count(3)
2

list.index(obj, i=0, j=len(list)) 在i<=k<j之間返回list[k]==obj的k值
>>> test_list.index(1234567890)
10
>>> test_list.index(3, 2, len(test_list)) #查找第二個3
9

list.sort()與list.reverse()無返回值
>>> test_list.sort()
>>> test_list
[0, 0.3, 3, 3, 8.9, 23, 33, 34, 54, 98, 100, 1234567890, 's', 'string']
>>> test_list.reverse()
>>> test_list
['string', 's', 1234567890, 100, 98, 54, 34, 33, 23, 8.9, 3, 3, 0.3, 0]

list.insert(index, value)插入元素
>>> test_list.insert(2, 'import this')
>>> test_list
['string', 's', 'import this', 1234567890, 100, 98, 54, 34, 33, 23, 8.9, 3, 3, 0.3, 0]

5.列表解析

列表解析的一般語法:[元素或者元素的操作 迭代(for) 條件(if)]

>>> new_list = [x ** 2 for x in range(0, 10) if x % 2 == 0]
>>> new_list
[0, 4, 16, 36, 64]

6.tuple

tuple可以看做不能改變的list掘猿,一旦被定義病游,不可改變
tuple的創(chuàng)建和訪問與list一樣,但是tuple不可更新稠通,更新意味著創(chuàng)建新的tuple
tuple不能刪除一個元素衬衬,只能del atuple全部刪除
所有多對象的、逗號分隔的改橘、沒有明確用符號定義的滋尉,這些集合的默認類型都是tuple
所有返回的多對象的都是元組類型

7.用列表構建其他數(shù)據(jù)類型

  • stack:先入后出
#!/usr/bin/env python
#-*- coding:utf-8 -*-

stack = []      #建立存儲的stack

#進棧
def pushit():
    stack.append(raw_input("Please Enter your String : ").strip())

#出棧
def popit():
    if len(stack) == 0:
        print "Connot pop from an Empty Stack!"
    else:
        print "Romove [", `stack.pop()`,"] successful!"

#觀察棧
def viewstack():
    print stack

CMDs = {'u': pushit, 'o': popit, 'v': viewstack}

#菜單
def showmenu():
    pr = """
    p(U)sh
    P(O)p
    (V)iew
    (Q)uit
    
    Enter choice: """
    while True:     #執(zhí)行命令
        while True:  #接受輸入
            try:
                choice = raw_input(pr).strip()[0].lower()
            except (EOFError, KeyboardInterrupt, IndexError):
                choice = 'q'

            print '\nYou picked: [%s]' % (choice)
            if choice not in 'uovq':
                print 'Invalid option, try again'
            else:
                break
        if choice == 'q':
            break
        CMDs[choice]()

if __name__ == '__main__':
    showmenu()
  • 隊列:先進先出
#!/usr/bin/env python
#-*- coding:utf-8 -*-

queue = []

# 進隊列
def enQ():
    queue.append(raw_input("Please Enter your String : ").strip())


# 出隊列
def delQ():
    if len(queue) == 0:
        print "Connot pop from an Empty Queue!"
    else:
        print "Romove [", `queue.pop(0)`, "] successful!"  #pop()函數(shù)默認為index = -1


# 觀察隊列
def viewqueue():
    print queue


CMDs = {'e': enQ, 'd': delQ, 'v': viewqueue}


# 菜單
def showmenu():
    pr = """
    (E)nterqueue
    (D)delqueue
    (V)iew
    (Q)uit

    Enter choice: """
    while True:  # 執(zhí)行命令
        while True:  # 接收輸入
            try:
                choice = raw_input(pr).strip()[0].lower()  # 確保接收輸入的第一個非空格字符的小寫字母
            except (EOFError, KeyboardInterrupt, IndexError):
                choice = 'q'

            print '\nYou picked: [%s]' % (choice)
            if choice not in 'devq':
                print 'Invalid option, try again'
            else:
                break
        if choice == 'q':
            break
        CMDs[choice]()


if __name__ == '__main__':
    showmenu()


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市飞主,隨后出現(xiàn)的幾起案子狮惜,更是在濱河造成了極大的恐慌,老刑警劉巖碌识,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件讽挟,死亡現(xiàn)場離奇詭異,居然都是意外死亡丸冕,警方通過查閱死者的電腦和手機耽梅,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來胖烛,“玉大人眼姐,你說我怎么就攤上這事诅迷。” “怎么了众旗?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵罢杉,是天一觀的道長。 經常有香客問我贡歧,道長滩租,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任利朵,我火速辦了婚禮律想,結果婚禮上,老公的妹妹穿的比我還像新娘绍弟。我一直安慰自己技即,他們只是感情好,可當我...
    茶點故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布樟遣。 她就那樣靜靜地躺著而叼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪豹悬。 梳的紋絲不亂的頭發(fā)上葵陵,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天,我揣著相機與錄音瞻佛,去河邊找鬼脱篙。 笑死,一個胖子當著我的面吹牛涤久,可吹牛的內容都是我干的。 我是一名探鬼主播忍弛,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼响迂,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了细疚?” 一聲冷哼從身側響起蔗彤,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疯兼,沒想到半個月后然遏,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡吧彪,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年待侵,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片姨裸。...
    茶點故事閱讀 39,754評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡秧倾,死狀恐怖怨酝,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情那先,我是刑警寧澤农猬,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站售淡,受9級特大地震影響斤葱,放射性物質發(fā)生泄漏。R本人自食惡果不足惜揖闸,卻給世界環(huán)境...
    茶點故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一揍堕、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧楔壤,春花似錦鹤啡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至隙畜,卻和暖如春抖部,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背议惰。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工慎颗, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人言询。 一個月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓俯萎,卻偏偏與公主長得像,于是被迫代替她去往敵國和親运杭。 傳聞我的和親對象是個殘疾皇子夫啊,可洞房花燭夜當晚...
    茶點故事閱讀 44,654評論 2 354

推薦閱讀更多精彩內容

  • http://python.jobbole.com/85231/ 關于專業(yè)技能寫完項目接著寫寫一名3年工作經驗的J...
    燕京博士閱讀 7,575評論 1 118
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn)辆憔,斷路器撇眯,智...
    卡卡羅2017閱讀 134,652評論 18 139
  • 個人筆記,方便自己查閱使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik閱讀 67,696評論 0 5
  • 主要內容源自解讀《Fluent Python》虱咧,理解如有錯誤敬請指正:-) Python標準庫提供了大量使用C來實...
    曉風翌日閱讀 2,644評論 0 2
  • 你會和什么樣的人做朋友熊榛? 這個問題其實很好回答。 你會和讓你舒服的人做朋友腕巡。 每個人都希望得到他人的關注玄坦,希望別人...
    艾米栗狂想曲閱讀 486評論 0 4