Python 自學的日子-- Two day(2)-python-列表-元組-字典,python-python-

來源:互聯網
上載者:User

Python 自學的日子-- Two day(2)-python-列表-元組-字典,python-python-

列表
格式:name = []
name = [name1, name2, name3, name4, name5]


#針對列表的操作

name.index("name1")#查詢指定數值的下標值name.count("name1")#查詢指定數值的總數name.clear("name")#清空列表name.reverse("name")#反轉列表數值name.sort("name")#排序,優先順序 特殊字元-數字-大寫字母-小寫字母name.extend("name1")#擴充。把另一個列表的值增加到當前列表

#增加 add

name.append("name5")#追加name.insert(1, "name1.5")#插入指定位置

#刪除 delete

name.remove("name1")#根據人名刪除del name[0]#根據下標刪除列表裡的值del name #刪除列表name.pop(0)#刪除指定下標的值,預設是最後一個

#查詢 select

print(name[0], name[2])#根據下標讀取print(name[0:2]) == print(name[:2])#切片  (連續的一段:顧頭不顧尾,0和-1都可以省略)print(name[-1])#-1 擷取最後一個位置的值print(name[-2:])#擷取最後兩個值,從前往後數最後一個是-1、依次是-3、-2、-1

#更改 update

name[1] = "name1.5"#更改指定下標的值

#列表copy分為深copy和淺copy


深copy 會把列表裡的子列表 copy過去

name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]name1 = copy.deepcopy(name)name[4][1] = "name7"name[1] = "name2.1"print(name)print(name1)

result(結果)

['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]['name1', 'name2', 'name3', 'name4', ['name5', 'name6']]


淺copy 只會copy列表的第一層,如果新檔案子列表裡的數值更改,老檔案子列表的值不會更改

name = ["name1", "name2", "name3", "name4", ["name5", "name6"]]name1 = name.copy() = copy.copy(name) = name[:] = list(name)name[4][1] = "name7"name[1] = "name2.1"print(name)print(name1)

result(結果)

['name1', 'name2.1', 'name3', 'name4', ['name5', 'name7']]['name1', 'name2', 'name3', 'name4', ['name5', 'name7']

 元組(不可變的列表)
格式:tuple = ("tu1", "tu2")
和列表一樣,不可增刪改。只能查詢(切片)

tuple = ("tup1", "tup2")print(tuple.count("tup1"))print(tuple.index("tup2"))

 

練習題:

程式:購物車程式

需求:

#購物車練習題shoplist = [[1, "iphone", 6000], [2, "mac pro", 12000], [3, "ipad air", 8000], [4, "chicken", 30], [5, "eggs", 5], [6, "bike", 500]]mall = []salary = int(input("please input your salary:"))while True:    for i in range(0, len(shoplist)):        print(shoplist[i])    goodid = int(input("Please enter the number you want to buy goods:")) - 1    if int(shoplist[goodid][2]) > salary:        print("Don't buy goods you want")    else:        mall.append(shoplist[goodid])        salary = salary - shoplist[goodid][2]    yesorno = input("To continue shopping?input Y or N")    if yesorno == 'N':        print("Do you have bought the goods:%s,remaining sum:%s" % (mall, salary))        print("Thanks for coming.")        break

 最佳化修正版本:

#最佳化版本splist = [("iphone", 6000),          ("mac pro", 12000),          ("ipad air", 8000),          ("chicken", 30),          ("eggs", 5),          ("bike", 500)          ]shop_list = []salary1 = input("please input your salary:")if salary1.isdigit():#判斷是否為數字    salary1 = int(salary1)    while True:        for index, i in enumerate(splist):            print(index + 1, i)        number = input("請輸入要選擇的商品序號:")        if number.isdigit():            if int(number) <= len(splist) and int(number) >= 0:                if splist[int(number) - 1][1] < salary1:                    shop_list.append(splist[int(number) - 1])                    salary1 -= splist[int(number) - 1][1]                    print("你已購買商品為:%s,餘額是\033[41;1m%s\033[0m" % (shop_list, salary1))                else:                    print("你的餘額為 \033[31;1m%s\033[0m ,選擇商品價格為%s,所以當前餘額不夠購買此商品,選購其他商品看看?!" % (salary1, splist[int(number) - 1][1]))            else:                print("沒有此商品,請重新選擇!")        elif number == 'N':            print("你已購買商品為:%s,餘額是\033[41;1m%s\033[0m" % (shop_list, salary1))            print("謝謝光臨,歡迎下次再來!")            exit()        else:            print("請輸入正確的商品編號!")else:    print("請輸入正確的工資!")

 

字典:(無序、無下標,根據key來尋找對應的value)
格式:
info = {"key": "value",}

dictionary = {"n1": "5000",             "n2": "5200",             "n3": "2300",             "n4": "9000"}#查詢print(dictionary["n2"])#在知道key是什麼的時候查詢,如果key不存在就報錯print(dictionary.get("n5"))#如果key不存在會返回none,存在就返回value。print("n2" in dictionary)#判斷key是否存在,返回true or false py2.7中格式是 dictionary.has_key("n3")#增加dictionary["n2"] = "5100"dictionary["n6"] = "800"print(dictionary)#刪除dictionary.pop("n7")del dictionary["n3"]#刪除已知key對應的值,不存在會報錯print(dictionary)#修改dictionary["n2"] = "5100"dictionary["n6"] = "800"#其他#valuesprint(dictionary.values())#查詢所有value,不輸出key#keysprint(dictionary.keys())#只輸出key#setdefaultdictionary.setdefault("n5", "100")#key若有就列印value,沒有就賦新value#update(相對於兩個字典來說使用,有相同的key就替換value,無則插入)dictionary = {"n1": "5000",             "n2": "5200",             "n3": "2300",             "n4": "9000"}dictionary1={    "n1": "8",    "n3": "10000",    "n6": "100",    "n7": "4000"}dictionary.update(dictionary1)print(dictionary){'n2': '5200', 'n4': '9000', 'n3': '10000', 'n7': '4000', 'n1': '8', 'n6': '100'}#items將字典轉換成列表print(dictionary.items())dict_items([('n2', '5200'), ('n3', '2300'), ('n4', '9000'), ('n1', '5000')])


#字典迴圈
方法一:

for i in dictionary:    print(i, dictionary[i])


方法二:  會把字典dictionary轉換成列表list,不建議使用

for key, value in dictionary.items():    print(key, value)

 

聯繫我們

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