【python3】快速上手(3) : 數組和字典

一、數組

#1.在列表中添加元素

message = ["1","2","3"]

message.append("4")

#2.在列表中插入元素

message.insert(0,"0")

#3.使用del語句刪除元素

del message[0]

#4.使用pop刪除尾部

message.pop()

#5.使用pop刪除任意處的元素

message.pop(1)

#6.根據值來刪除元素 remove

message = ["0","1","2","3","4"]

message.remove("2")

#7.使用方法sort對列表進行永久性排序

message.sort()

message.sort(reverse = True)

#臨時排序

print(sorted(message))

print(message)

 

#直接倒着排序

message.reverse()

print(message)

#確定列表的長度

print(len(message))

#使用列表時避免索引錯誤,主要是越界問題

 

二、字典

 

#字典

dic = {"x":0,"y":1,"z":4}

print(dic)

 

#添加內容

dic["w"] = 3

print(dic)

 

#刪除鍵值對

 

del dic["x"]

print(dic)


 

#遍歷鍵值對 item()

for key,value in dic.items():

    print(key)

    print(value)

 

for key in dic.keys():

    print(key)

 

#按順序遍歷字典中的所有鍵

 

for name in sorted(dic.keys()):

    print(name.title())


 

#遍歷字典中的所有值

 

for value in dic.values():

    print(value)

#嵌套

alient_0 = {'color':'green','points':5}

alient_1 = {'color':'yellow','points':10}

alient_2 = {'color':"red","points":15}


 

alients = [alient_0,alient_1,alient_2]

for alient in alients:

print(alient)

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章