1. 程式人生 > >詳解元組、列表、字典、集合

詳解元組、列表、字典、集合

下面我們要了解以下資料型別

  • 元組
  • 列表
  • 字典
  • 集合

一、元組(tuple)


1.元組的建立(可以把元組看作一個容器,任何資料型別都可以放在裡面)
  • 通過賦值方法建立元組
In [5]: t = ("hello",2.3,2,True,{1:"hello",2:"world"},)

In [6]: type(t)
Out[6]: tuple

In [7]: t = (1)

In [8]: type(t)
Out[8]: int

In [9]: t = (1,)    #定義單個元組,一定要在這個元組後面加","

In [10]: type(t)
Out[10]: tuple
  • 通過工廠方法建立元組
In [15]: t = tuple("hello")

In [16]: type(t)
Out[16]: tuple

2.元組的操作

  • 索引
In [17]: t = ("hello",2.3,2,True,{1:"hello",2:"world"},)

In [18]: print t[0]       #正向索引
hello

In [19]: print t[-1]      #反向索引
{1: 'hello', 2: 'world'}

In [20]: print t[4][1]    #取索引值為4的字典中key為1的value

hello
  • 切片
In [24]: t = ("hello",2.3,2,True,{1:"hello",2:"world"},)

In [25]: print t[2:4]    #只取索引為2,3的元素
(2, True)

In [26]: print t[::-1]   #逆轉元組的元素
({1: 'hello', 2: 'world'}, True, 2, 2.3, 'hello')
  • 連線
In [33]: t = (1,1.2,True,"hello") 

In [34]: t1 = ((True,"hello",1),1+2j)

In [35]: print t1+t
((True
, 'hello', 1), (1+2j), 1, 1.2, True, 'hello')
  • 重複
In [39]: t = (1,1.2,True,"hello")  

In [40]: print t*2       #自己指定重複次數
(1, 1.2, True, 'hello', 1, 1.2, True, 'hello')
  • 成員操作符(這裡常用於一些判斷語句)
In [41]: t = (1,1.2,True,"hello")

In [42]: "hello" in t
Out[42]: True

In [43]: "hello" not in t
Out[43]: False

這裡元組的一些操作,如索引、切片可以類比字串的特性來學習,詳見我的字串詳解這篇部落格

  • 元組的迴圈(元組是一個可迭代物件)
In [44]: vip = ("lucy","lili","xixi")

In [45]: for i in vip:    #迴圈輸出元組的各個元素
   ....:     print i
   ....:     
lucy
lili
xixi

test:埠掃描器

In [47]: ips = ("172.25.254.1","172,.25.254.13")

In [48]: ports = (20,21,80)

In [49]: for ip in ips:                 #for迴圈的巢狀
   ....:     for port in ports:
   ....:         print "[+] Scaning %s:%d" %(ip,port)  
   ....:         
[+] Scaning 172.25.254.1:20
[+] Scaning 172.25.254.1:21
[+] Scaning 172.25.254.1:80
[+] Scaning 172,.25.254.13:20
[+] Scaning 172,.25.254.13:21
[+] Scaning 172,.25.254.13:80

3.元組的常用方法

  • count()
    括號裡是元組的value,返回這個value出現的次數,若是該value不在這個元組內,則返回0
In [60]: t = (1,2,3,4,4,"hello")

In [61]: t.count(4)   #統計4出現的次數
Out[61]: 2

In [62]: t.count(6)
Out[62]: 0
  • index()
    這裡寫圖片描述
    檢視該方法的幫助幫助文件,括號裡可以填該元組的一個value,也可以選填該value的範圍(start,stop),預設step為1是,範圍是從索引為start到stop-1,返回的是該value的第一個索引
In [72]: t = (1,1,1,1,1,1)

In [73]: t.index(1)   #不指定value的範圍
Out[73]: 0

In [74]: t.index(1,1,3) #指定value的範圍在索引為1-2之間
Out[74]: 1

In [75]: t.index(1,2,4) #指定該value的範圍在索引為2-3之間
Out[75]: 2

4.元組可用的內建方法

  • cmp()
    兩個元組間第一個元素ASCII碼的比較,左邊大於右邊的元組,返回1,左邊小於右邊的元組,則返回-1,若是左右兩邊元組相等,則返回0
In [83]: cmp(("a",12),(1,2))   
Out[83]: 1
  • max()
    同上,但返回的是值大的元組
In [85]: max(("hello",2),(3,4))
Out[85]: ('hello', 2)
  • min()
    同上,但返回的是值小的元組
In [86]: min(("hello",2),(3,4))
Out[86]: (3, 4)
  • 列舉的使用

    採用元組套元組的方式,儲存成績資訊:

scores = (
    ("Math",90),
    ("English",91),
    ("Chinese",93.1)
)

利用列舉和for迴圈輸出資訊

print "科目編號\t科目名稱\t\t成績"
for index,value in enumerate(scores):
     print "%3d\t\t%s\t\t%.2f" %(index,value[0],value[1])

結果

科目編   科目名稱     成績
  0     Math        90.00
  1     English     91.00
  2     Chinese     93.10
  • zip()
    令元組a的元素和元組b的元素一一對應,若是兩個元組的元數個數不等,則以元素少的元組為標準,一一匹配完為止
In [99]: subjects = ("chinese","math","english")

In [100]: scores = (93.1,90)

In [101]: print zip(subjects,scores)
[('chinese', 93.1), ('math', 90)]

二、列表(list)


列表是打了激素的陣列,因為陣列只能儲存同一種資料型別的結構,而列表可以儲存是可以儲存多種資料型別的結構
1.定義列表
In [103]: li = [(1,2,3),"hello", [True,"world",666],1.2]

In [104]: print li
[(1, 2, 3), 'hello', [True, 'world', 666], 1.2]

In [105]: type(li)
Out[105]: list

2.列表的操作(和元組比較)

  • 索引(類似於元組,不贅述)
In [111]: li = [(1,2,3),"hello", [True,"world",666],1.2]

In [112]: print li[2][0]
True

列表是可變資料型別,可以修改元素

In [106]: li = [(1,2,3),"hello", [True,"world",666],1.2]

In [107]: li[0] = 1   #令列表索引值為0的元素變為1

In [108]: li          #列表被修改
Out[109]: [1, 'hello', [True, 'world', 666], 1.2]

元組是不可變資料型別,不可以修改元素

In [110]: t =(0,1)

In [111]: t[0] = 1  #報錯,如下圖

這裡寫圖片描述

  • 切片(類似於元組,不贅述)

  • 連線(類似於元組,不贅述)

  • 重複(類似於元組,不贅述)

  • 成員操作符(類似於元組,不贅述)

3.列表的增刪查改
列表的一些方法,以下增刪查改等會應用
這裡寫圖片描述

append()追加元素到列表的最後

# ip 白名單
allow_ip = ["172.25.254.1","172.25.254.3", "172.25.254.26" ]
allow_ip.append("172.25.254.250")
print allow_ip

執行效果:
['172.25.254.1', '172.25.254.3', '172.25.254.26', '172.25.254.250']

insert()增加元素到列表的指定位置

allow_ip = ["172.25.254.1","172.25.254.3", "172.25.254.26" ]
allow_ip.insert(0, "192.168.1.253")

執行效果:
['192.168.1.253', '172.25.254.1', '172.25.254.3', '172.25.254.2
6', '172.25.254.250']

extend()增加多個元素到列表最後

# ip 白名單
allow_ip = ["172.25.254.1","172.25.254.3", "172.25.254.26" ]
allow_ip.extend(["172.25.254.45", "172.25.56.21"])

執行效果:
['192.168.1.253', '172.25.254.1', '172.25.254.3', '172.25.254.2
6', '172.25.254.250', '172.25.254.45', '172.25.56.21']
1.刪除列表中遇到的第一個 value 值,如果該value值不存在,則報錯
#語法格式:li.remove(value) 

li = [1,2,45,6,8,0,1]
li.remove(1)
print li

執行效果:
[2, 45, 6, 8, 0, 1]

2.刪除列表中第 i 個索引值;
#語法格式: del li[index]

li = [1,2,45,6,8,0,1]
del li[5]
print li

執行效果:
[1, 2, 45, 6, 8, 1]

test:刪除除了第一個元素之外的其他索引值
li = [1,2,45,6,8,0,1]  
del li[1::]     
print li

執行效果:
[1]
3.根據索引刪除一個元素,並返回該元素,如果括號內沒有值,預設刪除最後一個元素,若是超過範圍的index,則報錯
#語法格式:li.pop(index)

li = [1,2,45,6,8,0,1]
li.pop(1)
print li

執行效果:
[1, 45, 6, 8, 0, 1]

4.刪除列表物件
li = [1,2,45,6,8,0,1]
del li
1.統計某個元素在列表中出現的次數
li = [1,2,45,6,8,0,1]
print li.count(1)

執行效果:
2

2.找到某個值在列表中的索引值
li = [1,2,45,6,8,0,1]
print li.index(1,1)  #value值為1,該值範圍的起始索引為1

執行效果:
6
# 通過列表的索引,對列表某個索引值重新賦值
li = [1,2,45,6,8,0,1]
li[1] = True
print li

執行效果:
[1, True, 45, 6, 8, 0, 1]

ok,我們詳講了增刪查改所用到的一些方法,那我們還有sort()和reverse()方法沒有詳講,那下面就可以詳講一下這兩個方法

  • sort() — 排序
    若都是數字,按照數字大小排序 ;若是字母的話,按照 ASCII 碼來排序;
    ps:檢視對應的 ASCII 碼 ? ord(‘a’)
li = [1,2,45,6,8,0,1]
li.sort()
print li

執行效果:
[0, 1, 1, 2, 6, 8, 45]
  • reverse()—逆轉
    我們實現逆轉除了前面講的切片方式,也可以使用改方法
li = [1,2,45,6,8,0,1]
li.reverse()
print li

執行效果:
[1, 0, 8, 6, 45, 2, 1]

4.元組講了那麼多,那我們來一道練習題吧~
使用者登入程式版本:

  • 使用者名稱和密碼分別儲存在列表中;
  • 使用者登入時,判斷該使用者是否註冊;
  • 使用者登入時,為防止黑客暴力破解, 僅有三次機會;
  • 如果登入成功,顯示登入成功(exit(), break).

知識點學習:
python中特有的while….else…語句
如果滿足while後面的語句,執行while迴圈的程式, 如果不滿足,執行else裡面的程式.
執行效果:
這裡寫圖片描述
程式碼如下:

usernames = ["freya","lili"]
passwords = ["123","456"]

trycount = 0
while trycount < 3:
    username = raw_input("username:").strip()
    if not username in usernames:
        print "使用者名稱不存在!!!"
        break
    password = raw_input("password:").strip()
    index = usernames.index(username)
    if password == passwords[index]:
        print  "登入成功!!!"
        break
    else:
        print "密碼不正確!!!"
        trycount +=1
else:
    print "已超過三次,稍後再試!!!"

5.列表構建棧和佇列資料結構

  • 棧—–先進後出(LIFO-first in last out)
    類似於往箱子裡面放書

程式碼如下:

#定義一個空列表
list = []
info = """
***********棧操作***********
    1).入棧
    2).出棧
    3).棧長度
    4).檢視棧
    5).退出
"""

while True:
    print info
    choice = raw_input("your choice:").strip()
    if choice == "1":
        value = raw_input("入棧元素:").strip()
        list.append(value)       #使用追加的方法,新入棧的元素就在棧尾
        print "%s成功入棧!!!" %(value)
    if choice == "2":
        if not list:
            print "棧為空!!!"
            continue
        value = list.pop()       #該刪除方式沒有引數時預設刪除最後一個棧元素
        print "%s出棧成功!!!" %(value)
    if choice == "3":
        if not list:
            print "棧為空!!!"
            continue
        print "棧的長度為%d" %(len(list))  #使用內建方法len()
    if choice == "4":
        if not list:
            print "棧為空!!!"
            continue   
        print "序號\t棧元素"
        for index,value in enumerate(list):
            print "%d\t%s" %(index,value)
    if choice == "5":
        exit()
else:
    print "輸入合法運算元!!!"
  • 佇列—–先進先出(FIFO)
    類似於去餐廳買飯排隊

程式碼如下:

list = []
info = """
***********佇列操作***********
    1).入隊
    2).出隊
    3).隊長度
    4).檢視隊
    5).退出
"""

while True:
    print info
    choice = raw_input("your choice:").strip()
    if choice == "1":
        value = raw_input("入隊元素:").strip()
        list.append(value)
        print "%s成功入隊!!!" % (value)
    if choice == "2":
        if not list:
            print "隊為空!!!"
            continue
        value = list.pop(0)  #由於隊是先進先出,指定要刪除的value的索引號,可以達到該效果
        print "%s出隊成功!!!" % (value)
    if choice == "3":
        if not list:
            print "隊為空!!!"
            continue
        print "隊的長度為%d" % (len(list))
    if choice == "4":
        if not list:
            print "隊為空!!!"
            continue
        print "序號\t隊元素"
        for index, value in enumerate(list):
            print "%d\t%s" % (index, value)
    if choice == "5":
        exit()
else:
    print "輸入合法運算元!!!"

ok~,總結棧和隊的操作,就是在出隊和出棧時候pop()使用上的小小區別

未完待續~~~~