python基礎day 07 字典和集合

2021-10-12 06:39:23 字數 3423 閱讀 8569

2.4 增/改

2.5 刪

三、字典相關操作

四、字典相關方法

集合二、數學集合運算

lst_stu =

['小明',30

,'110',90

,70]dic_stu =

dic1 =

print

(type

(dic1))#

d2 =

# 鍵不能為列表、字典、集合等可變資料

print

(d2[

true])

# 值可為任何型別的資料

d3 =

d4 =

print

(d3 == d4)

# true;字典無序

2.3.1 查單個值

字典[key]

dog =

print

(dog[

'name'

], dog[

'color'

])

字典.get(key, 預設值)

print

(dog.get(

'gender'))

# 公狗

print

(dog.get(

'gender'

,'母狗'))

# 公狗

print

(dog.get(

'age',2

))# 不改變原字典

print

(dog)

#

2.3.2 遍歷
for x in dog:

print

(x)# name gender color

for x in dog:

print

(dog[x]

)# 旺財 公狗 黃色

# 練習:

classes =[,

,,,,

,]# 不及格人數

print

('不及格人數:'

,sum([

true

for stu in classes if stu[

'score'

]<60]

))# 班級平均分

print

('班級平均分:'

,sum

([stu[

'score'

]for stu in classes])/

len(classes)

)

新增鍵值對/修改鍵對應的值

字典[key] = 值

d =

d['c']=

3print

(d)#

d['a']=

0print

(d)#

只新增不修改,設定預設值方法

字典.setdefault(key, value)

print

(d)#

d.setdefault(

'b',5)

print

(d)#

d.setdefault(

'd',4)

print

(d)#

刪除鍵值對

del 字典[key]

字典.pop(key)

print

(d)#

x = d.pop(

'b')

print

(d)#

print

(x)# 2

d1 =

d2 =

print

(d1 == d2)

key in 字典

print

('a'

in d1)

# true

print

('c'

in d1)

# false

sum,max,min,sorted

len(字典)

dict(資料)

seq =[(

1,2)

,['a',

'b']

,'cd'

]d =

dict

(seq)

print

(d)#

字典轉列表

print

(list

(d))

# [1, 'a', 'c'] - 將鍵key轉化為列表中的元素

d =

dict

.fromkeys(

'ab',[

1,2]

)print

(d)#

for k, v in d.items():

print

(k, v)

# 練習:

# 交換字典的鍵值位

d =new_d =

dict([

(v, k)

for k, v in d.items()]

)print

(new_d)

d =

d.update(

['ac'

,'cd',(

12,34)

])print

(d)#

s =

set()#

s1 =

# print

(type

(s),

type

(s1)

)

s2 =

# typeerror: unhashable type: 'list'

s =

print

(s)#

並集 |

交集 &

差集 -

對稱差集 ^

子集 >=

真子集 >

a =

b =print

(a | b)

# print

(a & b)

# print

(a - b)

# print

(a ^ b)

# print

(a >= b)

# false

print

(a <

)# true

黑馬python基礎班 day07

1 類屬性 在類裡面和方法外面定義的屬性稱為類屬性,類屬性屬於當前類。例項屬性 物件屬性 在init方法裡面定義的屬性稱為例項物件,例項屬性屬於某個物件。class person object 定義類屬性和例項屬性 類屬性 country 中國 skin color yellow def init ...

python學習系列 day07

一 執行緒與程序 1 threadlocal 定義為乙個全域性變數,每乙個執行緒可以訪問,但是其在各個執行緒之間的訪問是不相互影響。對於各個執行緒來將就是區域性變數。import threading local school threading.local 定義乙個threadlocal物件 def...

Python自學筆記 day07

當直譯器遇到import關鍵字,會去查詢對應的模組。查詢順序如下 當前目錄 sys模組中的path變數所有路徑 按預設搜尋路徑。import time print time.ctime 呼叫模組中的函式import首次匯入時會產生如下3步操作 1.首先開啟模組 2.然後執行對應的模組檔案,將執行過程...