Python基礎之列表、元組、字典、集合的使用

來源:互聯網
上載者:User

標籤:[]   wan   免費   最大   catalog   判斷   disjoint   餘額   系統   

一、列表

1、列表定義

names=["Jhon","Lucy","Michel","Tom","Wiliam"]

列表切片:

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",‘GuYun‘]print(names)print(names[0])print(names[1:3]) #不能取到索引為3的列表元素print(names[-1])#取列表的倒數第一位的值print(names[-2:]) #取倒數兩個值print(names[0:3])print(names[:3]) #與print(names[0:3]) 等價print(names.index("GuYun"))  # 列印輸出索引值print(names[names.index("GuYun")])print(names.count("LiYun"))  #列印輸出資料行表中"LiYun"的個數

 結果:

[‘HeXin‘, ‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘], ‘LiYun‘, ‘TianJun‘, ‘GuYun‘, ‘LiYun‘]HeXin[‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘]]LiYun[‘GuYun‘, ‘LiYun‘][‘HeXin‘, ‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘]][‘HeXin‘, ‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘]]5GuYun2

 2、列表元素的追加與刪除

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",‘GuYun‘,"LiYun"]print(names)#列表追加:names.append("李斯") #預設插入到列尾
names.insert(1,"唐宇") #指定位置插入
names[2]="肖靜" #指定位置插入
print("-----after append-----\n",names)#列表刪除:names.remove("LiYun")del names[1] #刪除列表中索引為1的值names.pop()#預設刪除最後一個值names.pop(0)#刪除第一個值print("-----after delete-----\n",names)

 運行結果:

[‘HeXin‘, ‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘], ‘LiYun‘, ‘TianJun‘, ‘GuYun‘, ‘LiYun‘]-----after append----- [‘HeXin‘, ‘唐宇‘, ‘肖靜‘, [‘caijie‘, ‘LiSi‘], ‘LiYun‘, ‘TianJun‘, ‘GuYun‘, ‘LiYun‘, ‘李斯‘]-----after delete----- [‘肖靜‘, [‘caijie‘, ‘LiSi‘], ‘TianJun‘, ‘GuYun‘, ‘LiYun‘]

刪除整個列表:del names 

反轉列表值的位置:name.reverse()

排序:names.sort()

3、列表複製

語句:import copy

列表擴充:

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",‘GuYun‘,"LiYun"]print(names)names2=[1,2,3,4]names.extend(names2) #將names2的值添加到names中print(names,names2)

 運行結果:

[‘HeXin‘, ‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘], ‘LiYun‘, ‘TianJun‘, ‘GuYun‘, ‘LiYun‘][‘HeXin‘, ‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘], ‘LiYun‘, ‘TianJun‘, ‘GuYun‘, ‘LiYun‘, 1, 2, 3, 4] [1, 2, 3, 4]

 列表複製與變數複製略有不同:

import copy#變數的複製:name1="LiHai"name2=name1name1="TianJun"print("-----name1>>",name1)print("-----name2>>",name2)#列表的複製:names=[‘1‘,‘2‘,‘3‘]names2=names.copy() #淺copynames[0] = 55print("-----names>>",names)print("-----names2>>",names2)names3=[1,2,[5,7],3]print("-----修改前的names3>>",names3)names4=copy.copy(names3) #淺copynames5=copy.deepcopy(names3) #深copynames3[2][0]=66names3[0]=88print("-----names3>>",names3)print("-----names4>>",names4)print("-----names5>>",names5)

 結果:

-----name1>> TianJun-----name2>> LiHai-----names>> [55, ‘2‘, ‘3‘]-----names2>> [‘1‘, ‘2‘, ‘3‘]-----修改前的names3>> [1, 2, [5, 7], 3]-----names3>> [88, 2, [66, 7], 3]-----names4>> [1, 2, [66, 7], 3]-----names5>> [1, 2, [5, 7], 3]

 變數name2被賦值之後不會隨name1的改變而改變,列表mames5在深copy的條件下,其結果與變數的複製效果一樣,並沒有隨names3的改變而改變;而列表names4通過淺copy後,其最外層不會隨names3的改變而改變,但內層會隨names3的改變而改變。

4、利用for迴圈列印列表names

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",‘GuYun‘,"LiYun"]for i in names:    print(i)

 結果:

HeXinZhangLiang[‘caijie‘, ‘LiSi‘]LiYunTianJunGuYunLiYun

 5、不用for迴圈列印列表

names=["HeXin","ZhangLiang",["caijie","LiSi"],"LiYun","TianJun",‘GuYun‘,"LiYun"]print(names[0:-1:2]) #列印列表中索引值為0到-1的值,步長為2print(names[::1]) #列印列表中所有值

 結果:

[‘HeXin‘, [‘caijie‘, ‘LiSi‘], ‘TianJun‘][‘HeXin‘, ‘ZhangLiang‘, [‘caijie‘, ‘LiSi‘], ‘LiYun‘, ‘TianJun‘, ‘GuYun‘, ‘LiYun‘]

 注意:列表列印屬於“顧頭不顧尾”,如print(names[0:2]) ,結果只能輸出資料行表的前兩個值。

利用列表書寫購物車程式:

(1)啟動程式後,讓使用者輸入工資,然後列印商品列表;

(2)使用者輸入相應的商品編號購買商品

(3)使用者輸入商品編號後,系統檢測餘額是否足夠,足夠則直接扣款,不夠則提示

(4)可隨時退出購物,並列印已購商品和餘額

shopping_list=[]product_list=[    [‘iphone‘,5800],    [‘mac pro‘,9800],    [‘bike‘,800],    [‘watch‘,10600],    [‘coffee‘,31]]salary=input(‘input your salary:‘)if salary.isdigit():    salary=int(salary)    while True:        for index, item in enumerate(product_list):#enumerate:讀取列表的索引            #print(product_list.index(item),item) 等價於上一句話            print(index,item)        user_choice=input(‘選擇要買什嗎?‘)        if user_choice.isdigit():#如果輸入的是數字            user_choice=int(user_choice)#將字元竄轉換為整型            if user_choice <len(product_list) and  user_choice>=0:#如果使用者輸入的數字在user_choice列表的長度範圍之內                p_item=product_list[user_choice]#product_list列表中商品價格賦值給p_item                if p_item[1] <= salary:                   shopping_list.append(p_item)                   salary-=p_item[1]                   print(‘Added %s into shopping cart,your current banlance is \033[31;1m%s\033[0m‘%(p_item,salary))                else:                   print(‘\033[41;1m你的餘額只剩[%s]啦\033[0m‘% salary)            else:                print(‘product code[%s] is not exist‘% user_choice)        elif user_choice==‘q‘:            print(‘....shopping list....‘)            for p in shopping_list:                print(p)            print(‘your current balance:‘,salary)            exit()        else:            print(‘Invalid option‘)

 二、元組

元組一旦建立不能修改,所以又叫唯讀列表。

元組只有兩個方法:count和index

元組定義:names=(‘Jim‘,‘Lucy‘)

三、字典

字典是一種Key-value的資料類型,是無序的。

1、字典相關操作

#字典定義 :info={‘stu001‘:‘Lily‘,      ‘stu002‘:‘Jack‘,      ‘stu003‘:‘John‘,}print(info)print(info[‘stu002‘]) #列印輸出stu002的值info["stu002"]="張三" #修改值info["stu004"]="HeQian" #新增#del info #刪除字典infodel info["stu001"]  #刪除指定值print("操作後的字典>>>",info)b={    ‘stu001‘:"yanlin",    1:3,    2:5}info.update(b)#更新字典print("更新後的字典>>>",info)c=info.fromkeys([6,7,8],"test")#初始化新字典,並給每個key賦值testprint("初始化後的字典>>>",c)print(info.items())#字典轉成列表c=dict.fromkeys([6,7,8],[1,{"name":"Micle"},234])#初始化新字典,三個key將共用一個值print(c)c[7][1][‘name‘]="Cherry"#修改字典值print(c)print("--------字典迴圈 ------")for i in info:    print(i,info[i])#推介使用此方法迴圈print("---------")for k,v in info.items():    print(k,v)

 結果:

{‘stu003‘: ‘John‘, ‘stu002‘: ‘Jack‘, ‘stu001‘: ‘Lily‘}Jack操作後的字典>>> {‘stu003‘: ‘John‘, ‘stu002‘: ‘張三‘, ‘stu004‘: ‘HeQian‘}更新後的字典>>> {1: 3, ‘stu002‘: ‘張三‘, ‘stu001‘: ‘yanlin‘, ‘stu004‘: ‘HeQian‘, ‘stu003‘: ‘John‘, 2: 5}初始化後的字典>>> {8: ‘test‘, 6: ‘test‘, 7: ‘test‘}dict_items([(1, 3), (‘stu002‘, ‘張三‘), (‘stu001‘, ‘yanlin‘), (‘stu004‘, ‘HeQian‘), (‘stu003‘, ‘John‘), (2, 5)]){8: [1, {‘name‘: ‘Micle‘}, 234], 6: [1, {‘name‘: ‘Micle‘}, 234], 7: [1, {‘name‘: ‘Micle‘}, 234]}{8: [1, {‘name‘: ‘Cherry‘}, 234], 6: [1, {‘name‘: ‘Cherry‘}, 234], 7: [1, {‘name‘: ‘Cherry‘}, 234]}--------字典迴圈 ------1 3stu002 張三stu001 yanlinstu004 HeQianstu003 John2 5---------1 3stu002 張三stu001 yanlinstu004 HeQianstu003 John2 5

 2、字典嵌套

av_catalog = {    "歐美":{        "www.youporn.com": ["很多免費的,世界最大的","品質一般"],        "www.pornhub.com": ["很多免費的,也很大","品質比yourporn高點"],        "letmedothistoyou.com": ["多是自拍,高品質圖片很多","資源不多,更新慢"],        "x-art.com":["品質很高,真的很高","全部收費,屌比請繞過"]    },    "日韓":{        "tokyo-hot":["品質怎樣不清楚,個人已經不喜歡日韓範了","聽說是收費的"]    },    "大陸":{        "1024":["全部免費,真好,好人一生平安","伺服器在國外,慢"]    }}av_catalog["大陸"]["1024"][1] += ",可以用爬蟲爬下來"#修改內容print(av_catalog["大陸"]["1024"]) #列印輸出被修改的內容av_catalog.setdefault("taiwan",{"www.baidu.com":[1,2]}) #新增字典元素print(av_catalog)av_catalog.setdefault("大陸",{"www.baidu.com":[1,2]})print(av_catalog)

 結果:

[‘全部免費,真好,好人一生平安‘, ‘伺服器在國外,慢,可以用爬蟲爬下來‘]{‘日韓‘: {‘tokyo-hot‘: [‘品質怎樣不清楚,個人已經不喜歡日韓範了‘, ‘聽說是收費的‘]}, ‘大陸‘: {‘1024‘: [‘全部免費,真好,好人一生平安‘, ‘伺服器在國外,慢,可以用爬蟲爬下來‘]}, ‘taiwan‘: {‘www.baidu.com‘: [1, 2]}, ‘歐美‘: {‘www.youporn.com‘: [‘很多免費的,世界最大的‘, ‘品質一般‘], ‘letmedothistoyou.com‘: [‘多是自拍,高品質圖片很多‘, ‘資源不多,更新慢‘], ‘x-art.com‘: [‘品質很高,真的很高‘, ‘全部收費,屌比請繞過‘], ‘www.pornhub.com‘: [‘很多免費的,也很大‘, ‘品質比yourporn高點‘]}}{‘日韓‘: {‘tokyo-hot‘: [‘品質怎樣不清楚,個人已經不喜歡日韓範了‘, ‘聽說是收費的‘]}, ‘大陸‘: {‘1024‘: [‘全部免費,真好,好人一生平安‘, ‘伺服器在國外,慢,可以用爬蟲爬下來‘]}, ‘taiwan‘: {‘www.baidu.com‘: [1, 2]}, ‘歐美‘: {‘www.youporn.com‘: [‘很多免費的,世界最大的‘, ‘品質一般‘], ‘letmedothistoyou.com‘: [‘多是自拍,高品質圖片很多‘, ‘資源不多,更新慢‘], ‘x-art.com‘: [‘品質很高,真的很高‘, ‘全部收費,屌比請繞過‘], ‘www.pornhub.com‘: [‘很多免費的,也很大‘, ‘品質比yourporn高點‘]}}

 3、三級菜單的實現

data = {    "北京":{        "朝陽":{            "yi":[‘炸雞‘,‘漢堡‘,‘03‘],            "er":[‘可樂‘,‘雪碧‘]        },        "昌平":{            "san":[‘06‘,‘益達‘,‘023‘],            "si":[‘米飯‘,‘玉米‘]        },    },    "四川":{        "成都": {            "雙流": [‘肥腸粉‘, ‘麻辣燙‘],            "新都": [‘燒烤‘, ‘滷雞腳‘]        },        "綿陽": {            "wu": [‘啤酒‘, ‘香檳‘, ‘鴨脖‘],            "liu": [‘檸檬‘, ‘橘子‘]        },    },    "安徽":{        "合肥": {            "qi": [‘011‘, ‘042‘, ‘063‘],            "ba": [‘104‘, ‘105‘]        },        "黃山": {            "jiu": [‘066‘, ‘07‘, ‘033‘],            "shi": [‘304‘, ‘025‘]        }    }}ch1=Falsewhile  not ch1:    for i in data:        print(i)    choice1=input(‘>>>:‘)    if choice1 in data:        while not ch1:            for i2 in data[choice1]:                print("\t",i2)            choice2 = input(‘>>>:‘)            if choice2 in data[choice1]:                while not ch1:                    for i3 in data[choice1][choice2]:                        print("\t\t",i3)                    choice3 = input(‘>>>:‘)                    if choice3 in data[choice1][choice2]:                            for i4 in data[choice1][choice2][choice3]:                                print("\t\t\t", i4)                            choice4=input(‘已經是最後一層,按b返回到上一級>>>:‘)                            if choice4=="b":                                pass                            elif choice4=="q":                                ch1=True                    if choice3 == "b":                        break                    elif choice3 == "q":                        ch1 = True            if choice2 == "b":                break            elif choice2 == "q":                ch1 = True

 四、集合

集合是一個無序的、不重複的資料群組合。

list1=[1,4,5,6,3,5,3,6] #定義一個列表list1=set(list1) #變成集合,去重list2=set([3,5,33,67,8,6])list3=set([3,5,6])list4=set([4,2])print(list1,type(list1))print(list1.intersection(list2))#取兩個集合的交集print(list1.union(list2))#取並集print(list1.difference(list2))#取差集,即在list1中有的,在list2中沒有的print(list1.issubset(list2))#子集print(list1.issuperset(list2))print(list3.issubset(list1))#list3是list1的子集print(list1.symmetric_difference(list2))#對稱差集,即取雙方互相沒有的值print("----------")print(list2.isdisjoint(list4))#判斷是否有交集print(list1 & list2)#交集print(list2 | list1)#並集print(list1 - list2)#差集print(list1 ^ list2)#對稱差集list4.add(78)#添加一個值list4.update([00,22])#添加多個值list4.remove(2)#刪除print(list4)print(list1.pop())#刪除任意一個值,並返回刪除的值print(list2.discard("34"))#刪除指定值,若不存在該值,系統不會報錯,有別於remove

 運行結果:

{1, 3, 4, 5, 6} <class ‘set‘>{3, 5, 6}{1, 33, 3, 4, 5, 6, 67, 8}{1, 4}FalseFalseTrue{33, 1, 67, 4, 8}----------True{3, 5, 6}{33, 1, 67, 3, 5, 6, 4, 8}{1, 4}{33, 1, 67, 4, 8}{0, 4, 78, 22}1None

 

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.