day07-總結(jié)

字典

1.什么是字典(dict)

字典是容器型數(shù)據(jù)類型(序列)版姑,將{ } 作為容器的標(biāo)志讨韭,里面多個元素用 , 隔開

1)

特點(diǎn):可變(支持增刪改)脂信,無序(不支持下標(biāo)操作)

2)字典中的元素

字典中的元素都是鍵值對,以 鍵:值 的形式成對出現(xiàn) - {key1:value1, key2:value2,...}
字典存儲數(shù)據(jù)主要為了存儲值透硝,鍵只是為了區(qū)分不同的值而存在的
鍵值對中的鍵 - 不可變狰闪;唯一的
鍵值對中的值 - 任何數(shù)據(jù)類型都可以作為值(和列表元素一樣)
list1 = {'x': 2, 'y': [123, 5], (1, 2): 'abba'}
print(list1)
# list1 = {'x': 2, 'y': [123, 5], [1, 2]: 'abba'}   # TypeError: unhashable type: 'list'
# print(list1)

# key是唯一的
list1 = {'x': 2, 'x': 7}  # 相同的 key 值 只保存最后一個
print(list1)                # {'x': 7}

class1 = {
    'name': 'zz',
    'add': 'xx',
    'head_teacher': {
        'name': 'ss',
        'tel': '11111111',
        'qq': '2222222'
    },
    'students': [
        {
            'name': 'qqw',
            'gender': '男',
            'id': '23132564865'
         },
        {
            'name': 'aqw',
            'gender': '男',
            'id': '23132564822'
        }
    ]
}

2.查 - 獲取字典的值

1)獲取單個元素的值

字典[key] - 獲取字典中指定key對應(yīng)的值(value)
字典.get(key) / 字典.get(key,默認(rèn)值) - 獲取字典中指定key對應(yīng)的值;如果key不存在返回None或者默認(rèn)值(是否寫入了默認(rèn)值)
dog = {'name': 'dd', 'age': 3, 'type': '中華田園', 'color': '灰色', 'gender': '母'}
print(dog['name'], dog['gender'])
# print(dog['weight'])  # KeyError: 'weight'

print(dog.get('age'), dog.get('color'))

# weight 不存在
print(dog.get('weight'))    # None
print(dog.get('weight', 'sssss'))    # sssss

2)獲取多個元素的值(遍歷)

遍歷字典直接取到的是鍵(key)

for key in 字典:
pass

for value in dog.values():
pass

for key,value in dag.items():
pass

常見的遍歷方式
dog = {'name': 'dd', 'age': 3, 'type': '中華田園', 'color': '灰色', 'gender': '母'}
2.1)
print("---------------------")
for key in dog:
    print(key)  # 取出key
    print(dog[key])  # 取出值
    pass
print("---------------------")
2.2)
for value in dog.values():
    print(value)
    pass
print("---------------------")
2.3)
print(dog.items())
for key, value in dog.items():
    print(key, value)
    pass
print("---------------------")

3.增和改

增 - 添加鍵值對;
改 - 修改字典中某個key對應(yīng)的值
語法: 字典[key] = 值 - 當(dāng) key 不在字典中濒生,添加進(jìn)入字典相應(yīng)的鍵值對埋泵;當(dāng) key 在字典中,修改對應(yīng)的鍵值對中的值

dict2 = {'a': 1, 'b': 2}
print(dict2)
dict2['c'] = 3
print(dict2)

dict2['a'] = 100
print(dict2)

4.刪 - 刪除 key 對應(yīng)的值

1)del 字典[key] - 刪除字典中對應(yīng) key 的鍵值對

2)字典.pop(key) - 取出字典中 key 對應(yīng)的值;返回被取出來的值

dict2 = {'a': 100, 'b': 2, 'c': 3}
del dict2['a']
print(dict2)

dict2 = {'a': 100, 'b': 2, 'c': 3}
value = dict2.pop('a')
print(dict2)
print(value)

5.相關(guān)運(yùn)算

# print({'a': 10} + {'b': 20})  # TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
import dic as dic
字典不支持 + * > >= < <=
支持; == !=

print({'a': 10, 'b': 20} == {'a': 10, 'b': 20}) # True
print({'a': 10, 'b': 20} == {'b': 20, 'a': 10}) # True

6.相關(guān)操作:in / not in

key in 字典 - 判斷字典中是否存在某個鍵
max 丽声、 min 礁蔗、 sum - 針對的是 key 的操作
dict(數(shù)據(jù)) - 將指定的數(shù)據(jù)轉(zhuǎn)換成字典
數(shù)據(jù)的要求:
1)數(shù)據(jù)本身就是一個序列
2)序列中的元素必須是有且只有兩個元素的小序列 [[元素11, 元素12], (元素21雁社, 元素22)]
print(2 in {'a': 10, 'b': 20})  # False
print('a' in {'a': 10, 'b': 20})  # True

dict1 = {'a': 1, 'b': 2, 'c': 3, 'z': 1}
print(max(dict1))  # 判斷 key 的大小  z
print(min(dict1))    # a

dict2 = {10: 11, 20: 21, 30: 31}
print(sum(dict2))  # 60 鍵相加

print(len(dict2))

# print(dict([[1, 2], (1, 2), 'a']))

7.相關(guān)方法

字典.clear()
dict1 = {'NAME': 'Tony', 'AGE': 18, 'gender': '男',
       'chinese': 89, 'math': 90, 'height': 180, 'weight': 67}
dict1.clear()
print(dict1)
dict.fromkeys(序列, 值1 = None) - 創(chuàng)建一個新的字典浴井,將序列中的元素作為字典的key,將之1作為每隔個key對應(yīng)的value
new_dict = dict.fromkeys('abc')
print(new_dict)    # {'a': None, 'b': None, 'c': None}

new_dict = dict.fromkeys(range(10, 16), 100)
print(new_dict)    # {10: 100, 11: 100, 12: 100, 13: 100, 14: 100, 15: 100}
2)字典.items() - 將字典中的鍵值對轉(zhuǎn)換成元祖作為容器中的元素
dict1 = {'NAME': 'Tony', 'AGE': 18, 'gender': '男',
       'chinese': 89, 'math': 90, 'height': 180, 'weight': 67}
print(dict1.items())   # dict_items([('NAME', 'Tony'), ('AGE', 18), ('gender', '男'), ('chinese', 89), ('math', 90), ('height', 180), ('weight', 67)])
3)字典.values(),字典.keys()
print(dict1.values(),dict1.keys())   # dict_values(['Tony', 18, '男', 89, 90, 180, 67]) dict_keys(['NAME', 'AGE', 'gender', 'chinese', 'math', 'height', 'weight'])
4)字典.setdefault(key, value = None) - 在字典中添加鍵值對(key 存在的時候不會有修改作用)
dict1.setdefault('long', 180)
print(dict1)  # {'NAME': 'Tony', 'AGE': 18, 'gender': '男', 'chinese': 89, 'math': 90, 'height': 180, 'weight': 67, 'long': 180}

dict1.setdefault('heigt', 180)
print(dict1)
5) 字典1.update(字典2) - 講字典2中的鍵值對全部添加到字典1中(相同的會后面加的覆蓋前面的值)
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'x': 100, 'y': 200, 'c': 300}
dict1.update(dict2)
print(dict1)  # {'a': 1, 'b': 2, 'c': 300, 'x': 100, 'y': 200}

dict1.update([(2, 3), (4, 5)])
print(dict1)  # {'a': 1, 'b': 2, 'c': 300, 'x': 100, 'y': 200, 2: 3, 4: 5}
練習(xí):用一個列表保存五只狗的信息霉撵,每只狗有:名字磺浙、年齡、顏色和體重
1)求5只狗的平均年齡 2)找到五只狗體重最大的狗的名字
list_dog = [
    {'name': 'aa', 'age': 2, 'color': 'write', 'weight': 20},
    {'name': 'bb', 'age': 5, 'color': 'write', 'weight': 32},
    {'name': 'cc', 'age': 4, 'color': 'write', 'weight': 34},
    {'name': 'dd', 'age': 7, 'color': 'write', 'weight': 33},
    {'name': 'ee', 'age': 3, 'color': 'write', 'weight': 35}
            ]
max_weight = list_dog[0]['weight']
sum_age = 0
for i in range(len(list_dog)):
    sum_age += list_dog[i]['age']
    pass
ave_age = sum_age / len(list_dog)
print(ave_age)

for i in range(len(list_dog)):
    for j in range(len(list_dog)):
        if list_dog[j]['weight'] > list_dog[i]['weight']:
            print(list_dog[j]['name'])
            break

集合

1.什么是集合(set)

集合是容器型數(shù)據(jù)類型(序列)徒坡;將{ }作為容器的標(biāo)志撕氧,多個元素用 , 隔開(和字典不一樣,集合的元素是獨(dú)立的數(shù)據(jù)不是鍵值對)
特點(diǎn):可變(增刪)喇完、無序(不支持下標(biāo)操作)
注意:{}表示空字典
元素 - 不可變數(shù)據(jù)伦泥;同一個元素只能有一個(唯一性)
set1 = {}
print(type(set1))  # <class 'dict'>
set2 = set()
print(set2)  # set()
集合中的元素不可變
# set2 = {'abc', [1, 2]}  # TypeError: unhashable type: 'list'
# set3 = {{'a': '5'}, True}   # TypeError: unhashable type: 'dict'
# a = 5
# set4 = {a, True, {4, 3}}  # TypeError: unhashable type: 'set'
集合自帶去重功能
set6 = {1, 2, 3, 5, 1, 1, 2}
print(set6)   # {1, 2, 3, 5}

scores = [34, 90, 89, 23, 34, 89, 100, 99]
scores = list(set(scores))
print(scores)   # [34, 99, 100, 23, 89, 90]

2.集合元素的增刪改查

1)查 - 只支持遍歷,不能單獨(dú)獲取具體某一個元素(遍歷出的值無序)
names = {'ss', 'aa', 'bb', 'ee'}
for item in names:
    print(item, end=' ')  # ee bb aa ss
2)增
集合.add(元素) - 不會產(chǎn)生新集合何暮,只修改原集合
集合.update(序列)- 將序列(不可變的)中的所有元素添加到原集合中
names.add('qq')
print(names)  # {'aa', 'bb', 'ee', 'qq', 'ss'}

names.update({100, 200})
print(names)   # {'aa', 'bb', 100, 200, 'ee', 'qq', 'ss'}
3) 刪
集合.remove(元素) - 刪除集合中指定的元素
names = {'ss', 'aa', 'bb', 'ee'}
names.remove('ss')
print(names)  # {'bb', 'aa', 'ee'}
4) 改(集合不支持修改元素的操作)

3.集合的相關(guān)方法

1).集合的數(shù)學(xué)運(yùn)算:
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
求并集 :集合1 | 集合2
print(set1 | set2)  # {1, 2, 3, 4, 5, 6, 7, 8, 9}
求交集 : 集合1 & 集合2
print(set1 & set2)  # {4, 5, 6}
求差集:集合1 - 集合2 (獲取集合1中除集合2的部分)
print(set1 - set2)  # {1, 2, 3}
print(set2 - set1)  # {8, 9, 7}
對稱差集:集合1 ^ 集合2 (兩個集合的并集對兩個集合的交集求差集)
print(set1 ^ set2)  # {1, 2, 3, 7, 8, 9}
集合1 > 集合2 判斷集合2是否包含于集合1(集合1包含集合2)
print(set2 > set1)  # False
集合1 < 集合2 判斷集合1是否包含于集合2(集合2包含集合1)
print(set2 > set1)

2)集合的方法

移除集合中的所有元素 clear()
set1 = {1, 2, 3, 4, 5, 6}
print(set1.clear())   # None
拷貝一個集合 copy()
set1 = {1, 2, 3, 4, 5, 6}
print(set1.copy())  # {1, 2, 3, 4, 5, 6}
difference() 返回多個集合的差集
set1 = set.difference({1, 2, 3, 4, 5, 6, 7}, {1, 2}, {6, 7})
print(set1)  # {3, 4, 5}
difference_update() 移除集合中的元素奄喂,該元素在指定的集合也存在。
set1 = {1, 2, 3, 4, 5, 6}
set2 = {5, 6, 7}
set1.difference_update(set2)
print(set1)   # {1, 2, 3, 4}
discard() 刪除集合中指定的元素 - 該方法不同于 remove() 方法海洼,因?yàn)?remove() 方法在移除一個不存在的元素時會發(fā)生錯誤跨新,而 discard() 方法不會。
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)  # {'apple', 'cherry'}
intersection() 返回集合的交集
set1 = {1, 2, 3, 4, 5, 6}
set2 = {5, 6, 7}
z = set1.intersection(set2)
print(z)   # {5, 6}
intersection_update() 返回集合的交集
intersection_update() 方法不同于 intersection() 方法坏逢,因?yàn)?intersection() 方法是返回一個新的集合域帐,而 intersection_update() 方法是在原始的集合上移除不重疊的元素。
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
x.intersection_update(y)
print(x)  # {'apple'}
isdisjoint() 判斷兩個集合是否包含相同的元素是整,如果沒有返回 True肖揣,否則返回 False
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.isdisjoint(y)
print(z)   # False
issubset() 判斷指定集合是否為該方法參數(shù)集合的子集。
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)   # True
issuperset() 判斷該方法的參數(shù)集合是否為指定集合的子集
x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
z = x.issuperset(y)
print(z)   # True
pop() 隨機(jī)移除元素
fruits = {"apple", "banana", "cherry"}
fruits.pop()
print(fruits)   # {'banana', 'apple'}
remove() 移除指定元素 (如果移除的元素不在原集合中會報(bào)錯)
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)  # {'apple', 'cherry'}
symmetric_difference() 返回兩個集合組成的新集合浮入,但會移除兩個集合的重復(fù)元素
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.symmetric_difference(y)
print(z)   # {'google', 'banana', 'runoob', 'cherry'}
symmetric_difference_update() 移除當(dāng)前集合中在另外一個指定集合相同的元素龙优,并將另外一個指定集合中不同的元素插入到當(dāng)前集合中。
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
x.symmetric_difference_update(y)
print(x)    # {'runoob', 'google', 'cherry', 'banana'}
union() 返回兩個集合的并集
x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
z = x.union(y)
print(z)  # {'apple', 'google', 'runoob', 'cherry', 'banana'}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末事秀,一起剝皮案震驚了整個濱河市彤断,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌易迹,老刑警劉巖宰衙,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異睹欲,居然都是意外死亡供炼,警方通過查閱死者的電腦和手機(jī)一屋,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來袋哼,“玉大人冀墨,你說我怎么就攤上這事∠孺遥” “怎么了轧苫?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長疫蔓。 經(jīng)常有香客問我含懊,道長,這世上最難降的妖魔是什么衅胀? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任岔乔,我火速辦了婚禮,結(jié)果婚禮上滚躯,老公的妹妹穿的比我還像新娘雏门。我一直安慰自己,他們只是感情好掸掏,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布茁影。 她就那樣靜靜地躺著,像睡著了一般丧凤。 火紅的嫁衣襯著肌膚如雪募闲。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天愿待,我揣著相機(jī)與錄音浩螺,去河邊找鬼。 笑死仍侥,一個胖子當(dāng)著我的面吹牛要出,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播农渊,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼患蹂,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了砸紊?” 一聲冷哼從身側(cè)響起传于,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎批糟,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體看铆,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡徽鼎,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片否淤。...
    茶點(diǎn)故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡悄但,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出石抡,到底是詐尸還是另有隱情檐嚣,我是刑警寧澤,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布啰扛,位于F島的核電站嚎京,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏隐解。R本人自食惡果不足惜鞍帝,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望煞茫。 院中可真熱鬧帕涌,春花似錦、人聲如沸续徽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽钦扭。三九已至纫版,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間土全,已是汗流浹背捎琐。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留裹匙,地道東北人瑞凑。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像概页,于是被迫代替她去往敵國和親籽御。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 一惰匙,字典 1.什么是字典(dict) 1)字典 字典是容器型數(shù)據(jù)類型(序列), 將{}作為容器的標(biāo)志技掏,里面多個元素...
    oct___d38e9閱讀 213評論 0 2
  • 認(rèn)識列表 1、列表是python中的容器類數(shù)據(jù)類型项鬼,可以用來存儲多個數(shù)據(jù)是可變的哑梳,有序的可變是指列表中元素的值、位...
    Heyjoky閱讀 152評論 0 1
  • (一)、主要內(nèi)容 1.1祭隔、列表 1.2货岭、元祖 1.3、字典 1.4疾渴、集合列表 千贯、字典、元祖程奠、集合 (二)丈牢、列表 2...
    IIronMan閱讀 3,555評論 0 7
  • 1.基本使用 1.1 數(shù)據(jù)類型 常用數(shù)據(jù)類型 Common Data Types 其他類型 Others 1.2 ...
    suwi閱讀 1,356評論 0 3
  • 把我的頭發(fā)繩子上的金屬吃了,劃破腸道瞄沙,早上便血己沛,一天都不能吃東西,晚上帶尼莫去拍片距境。跟思慧討論了如何做視頻申尼,還幫我...
    葉子卷閱讀 161評論 0 1