Python3快速入门----(3) dict(字典结构)
轉載地址:https://blog.csdn.net/asialee_bird/article/details/79560355
#先回憶列表的操作
animals=["cat", "dog", "rabbit"] #找到list中某個值(第一種方法)
for animal in animals:
? ? if (animal == "cat"):
? ? ? ? print("Cat found")
animals = ["cat", "dog", "rabbits"] #找到list中的某個值(第二種方法)
if "cat" in animals:
? ? print("Cat found")
student=["Tom", "Jim", "Sue", "Ann"] # 找到某人所得分數
scores=[70,80,85,75]
indexes=[0,1,2,3]
name="Sue"
score=0
for i in indexes:
? ? if student[i] == name:
? ? ? ? score = scores[i]
? ? ? ? print(score)
# 字典結構
scores={} #<class 'dict' > Dictionaries 字典結構key value(鍵值一一對應)
scores['Jim']=80
scores['Sue']=85
scores['Ann']=75
print(scores.keys())? #dict_keys(['Jim', 'Sue', 'Ann'])? 字典中的key
print(scores) #{'Jim': 80, 'Sue': 85, 'Ann': 75}? 輸出字典中的鍵和值
print(scores["Sue"]) #輸出鍵所對應的值 結果為85
?
students={"Tom":60, "Jim": 70} #創建字典并初始化鍵值
students["Jim"] = 65 #更改字典中某個鍵的值
print('Tom' in students) #判斷鍵是否在字典中
?
#用字典結構做統計數
pantry=["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "patato", "grape"]
pantry_counts=[]
for item in pantry: #對list進行遍歷
? ? if item in pantry_counts:
? ? ? ? pantry_counts[item]=pantry_counts[item]+1
? ? else:
? ? ? ? pantry_counts[item] = 1
? ? ? ? print(pantry_counts)? #輸出結構{'apple': 3, 'orange': 2, 'grape': 2, 'tomato': 1, 'patato': 1}
補充: dict和set
和list比較,dict有以下幾個特點:
? (1) 查找和插入的速度極快,不會隨著key的增加而變慢;
? (2) 需要占用大量的內存,內存浪費多。
而list相反:
? (1) 查找和插入的時間隨著元素的增加而增加;
? (2) 占用空間小,浪費內存很少。
#set和dict類似,也是一組key的集合,但不存儲value。由于key不能重復,所以,在set中,沒有重復的key
#set可以看成數學意義上的無序和無重復元素的集合,因此,兩個set可以做數學意義上的交集、并集等操作。
s1=set([1,2,3,4,5,6]) #創建一個set,需要提供一個list作為輸入集合
s2=set([2,3,4,9,8])
print(s1&s2)? #交集結果{{2,3,4}
print(s1|s2) #并集結果 {1,2,3,4,5,6,8,9}
s1.add(11)? #add(key)方法可以添加元素到set中,可以重復添加,但不會有效果
s1.remove(1) #通過remove(key)方法可以刪除元素
?
?
總結
以上是生活随笔為你收集整理的Python3快速入门----(3) dict(字典结构)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3--unitest框架的使
- 下一篇: Python断言方法:assert