2018-10-09字典和元祖

元祖


1.什么是元祖

a.
是容器,可以存儲(chǔ)多個(gè)數(shù)據(jù),不可變,有序的
不可變:不能增刪改
有序:可以通過(guò)下標(biāo)獲取

b.
元素,可以是任何類型的數(shù)據(jù)

注意:如果元祖的元素只有一個(gè),則必須在后面加逗號(hào)表示一個(gè)元祖

tuple1 = (100,)
print(tuple1)

tuple1 = 10, 20, 'abc'   # 也是元祖(多個(gè)數(shù)據(jù)用逗號(hào)隔開(kāi)表示的也是元祖)
print(tuple1)

2.元祖:不支持增刪改,但可以查

列表獲取元素的方式,元祖都支持
元祖[下標(biāo)] 或 元祖[ : : ]

tuple2 = '星期一', '星期二', '星期三', '星期四'
print(tuple2[0])
print(tuple2[2:])
print(tuple2[ : : -1])

#### 3.遍歷元祖
for item in tuple2:
    print(item)

index = 0
while index < len(tuple2):
    print(tuple2[index])
    index += 1

4.補(bǔ)充:獲取部分元素:可以通過(guò)相同的變量個(gè)數(shù),來(lái)一一獲取元祖中的元素

x, y = (10, 20)
print(x, y)

x, y, z = 10, 20, 30
print(x, y, z)
應(yīng)用:交換兩個(gè)數(shù)的值
a = 10
b = 20
方法1:
t = a
a = b
b = t

方法2:
a, b = b, a
print(a, b)

5.可以通過(guò)在變量前加*來(lái)獲取部分元素(適用列表)

tuple2 = ( 90, 80, 70, '小明')
name, *score = tuple2
print(name, score)

*score, name = tuple2
print(name, score)

6.可以在列表或元祖前加*,來(lái)展開(kāi)列表中的元素

tuple3 = ( 90, 80, 70, '小明')
print(*tuple3)

list1 = ['abc', '100', '200']
print(*list1)

7.元祖運(yùn)算

>, +, *, ==, is, in, not in

print((1, 2, 3) + ('z', 'c', 'b'))
print((1,2) * 2)
print((1,2,3) == (1, 2, 3))
print((1,2,3) is (1,2,3))
print((1,2) in (1,2,3))
print((1,2,3) not in (1,2,3))

8.元祖支持的函數(shù)方法

  • len()
  • max()
  • min()

9.tuple()

所有的序列都可以轉(zhuǎn)換成元祖,注意:字典只能將key值作為元祖元素

print(tuple('abcd'))

10.sorted()

排序后產(chǎn)生一個(gè)新的列表

tuple4 = (1,2,3,8,0,4)
tuple5 = sorted(tuple4)
print(tuple4)
print(tuple5)

11.需要存儲(chǔ)多個(gè)數(shù)據(jù)時(shí)就用容器

什么時(shí)候用列表:保存同一類數(shù)據(jù)時(shí)用列表
什么時(shí)候用字典:需要區(qū)分?jǐn)?shù)據(jù)意義時(shí)就要字典
什么時(shí)候用元祖: 保存同一類數(shù)據(jù)時(shí)用列表,并且不可變時(shí)

字典


12.什么是字典

字典是一個(gè)容器類的數(shù)據(jù)類型,可以用來(lái)存儲(chǔ)多個(gè)數(shù)據(jù)(鍵值對(duì)的形式存儲(chǔ)數(shù)據(jù))
{key1:value1, key2:value2, .....}
字典是可變的(可以增刪改),無(wú)序的(不能用下標(biāo)獲取值)
key:用來(lái)定位值的。要求:唯一性,只能是不可變的數(shù)據(jù)類型(數(shù)字,字符串,元祖....)
值:存放數(shù)據(jù),可以是任何類型的數(shù)據(jù)

student = {'name':'xiaoming', 'age':'18', 'math':80, 'english':90,'chinese':90}
print(student['name'])

13.查(獲取value)

獲取字典的值必須通過(guò)key來(lái)獲取
每次只能獲取單個(gè)值
a.
語(yǔ)法:字典[key] 獲取key對(duì)應(yīng)的值
key必須存在,否則報(bào)錯(cuò)
b.
字典.get(key) :獲取key對(duì)應(yīng)的值
key不存在時(shí)不會(huì)報(bào)錯(cuò),返回一個(gè)none
注意:key一定存在時(shí)用字典[key],當(dāng)key可能存在可能不存在時(shí)用字典.get()方法

student = {'name':'xiaoming', 'age':'18', 'math':80, 'english':90,'chinese':90}
print(student['math'])
print(student.get('math'))
print(student.get('kkkk')) # 返回None

14.直接遍歷字典(拿到key推薦使用)

student = {'name':'xiaoming', 'age':'18', 'math':80, 'english':90,'chinese':90}
for x in student:
    print(x, student[x])

15.其他方式遍歷(占cpu)

a.直接遍歷獲取值

for value in student.values():
    print(value)

b.直接遍歷獲取key-value

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

17.添加鍵值對(duì)

  • 語(yǔ)法:dict[key] = value(key不存在)
car = {}
car['color'] = 'red'
print(car)

18.修改

  • 語(yǔ)法:dict[key] = value(key存在)
car = {}
car['color'] = 'red'
car['color'] = 'black'
print(car)

19.刪除鍵值對(duì)

  • a.
    語(yǔ)法:del dict[key] 通過(guò)key刪除鍵值對(duì)

  • b.
    語(yǔ)法:dict.pop(key) 取出key對(duì)應(yīng)的值,但相對(duì)來(lái)說(shuō)就是刪除鍵值對(duì)

student = {'name':'xiaoming', 'age':'18', 'math':80, 'english':90,'chinese':90}
del student['age']
print(student)

name = student.pop('name')
print(student, name)

20.字典相關(guān)運(yùn)算

字典不支持+,* 運(yùn)算
但只支持 == 運(yùn)算,但字典長(zhǎng)度要相同,字典是無(wú)序的
字典也支持 is,in,not in
注意:key in dict 或者 key not in dict

print({'a': 100, 'b':200} == {'b': 200, 'a': 100})
print({'a': 100, 'b':200} is {'b': 200, 'a': 100})
print('a' in {'a': 100, 'b':200})
print('a' not in {'a': 100, 'b':200})

21.字典相關(guān)函數(shù)和方法

  • len(dict)
    獲取鍵值對(duì)的個(gè)數(shù)

  • dict.clear()
    清空字典所有的鍵值對(duì)

  • dict.copy()
    復(fù)制一份所有的鍵值對(duì),產(chǎn)生一個(gè)新的字典

dict1 = {1,5,8,9}
dict2 = dict1.copy()
print(dict2)
  • dict.fromkeys(序列,值)
    將序列中的每個(gè)元素作為key,后面的值作為value
dict3 = dict.fromkeys('xyz', 100)
print(dict3)  #{'x': 100, 'y': 100, 'z': 100}
  • dict.get(key) # key不存在時(shí)返回none
  • dict.get(key, 默認(rèn)值) # key不存在時(shí)取默認(rèn)值
student = {}
print(student.get('name'))
print(student.get('name', '無(wú)名'))
  • dict.values()
    直接獲取所有的value序列

  • dict.keys()
    直接獲取所有key的序列

  • dict.items()
    將鍵值對(duì)轉(zhuǎn)換成元祖,作為一個(gè)序列的元素
    注意:返回的都不是列表,是其他類型的序列

  • dict.setdefault(key)

  • dict.setdefault(key, 值)
    key存在時(shí)對(duì)字典沒(méi)有任何效果,key不存在時(shí)會(huì)添加一個(gè)新的鍵值對(duì)(key為空時(shí)默認(rèn)為none)

student = {}
student.setdefault('aa', 100)
print(student)

student.setdefault('aa')
print(student)
  • dict1.update(dict2)
    使用2中的鍵值對(duì)去更新字典2(已經(jīng)存在的key就更新,不存在的就添加)
dict1 = {'a': 1, 'b': 2}
dict2 = {'a': 100, 'c': 500}

dict1.update(dict2)
print(dict1)
print(dict2)

集合


22.什么是集合(set)

集合也是容器,集合是可變的,無(wú)序的
可變:能增刪改
無(wú)序:不能通過(guò)下標(biāo)獲取元素
形式:{元素1,元素2....}
元素:必須是不可變的數(shù)據(jù),并且元素具有唯一性,則集合自帶去重的功能

set1 = {1, 'asd', 45, (10, 200)}
print(set1)

注意:set2 = {}表示字典,而不是集合

23.集合的查(獲取)

  • a.
    集合不能單獨(dú)獲取一個(gè)元素,不能切片,只能通過(guò)for-in來(lái)遍歷
set1 = {1, 'asd', 45, (10, 200)}
for x in set1:
    print(x)

24.增加元素

  • a.
    set.add(元素) :集合中添加一個(gè)元素
    set1 = {1, 'asd', 45, (10, 200)}
    set1.add(5)
    print(set1)

  • b.
    set1.update(set2) :將集合2中的元素添加到集合1中,相當(dāng)于數(shù)學(xué)求并集

set2 = {'zzz', 'aaa'}
set1.update(set2)
print(set1)

set2.update('789')
print(set2)  #{'aaa', 'zzz', '9', '7', '8'}

set2.update(['abc', 'uuu'])
print(set2)         # 列表元素必須是不可變的

set2.update({'name': 520})
print(set2)         # 字典只能把key添加到集合中

25.刪除

集合就一種刪除方法
語(yǔ)法:集合.remove(元素)

注意:集合不能改

26.集合相關(guān)運(yùn)算

包含,交集,并集,補(bǔ)集,差集

27.包含

運(yùn)算符: >= 和 =<
集合1 >= 集合2 : 判斷集合1是否包含集合2
集合1 <= 集合2 : 判斷集合2是否包含集合1

set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3,}
print(set1 >= set2)
print(set2 <= set1)

28.交集

求兩個(gè)集合公共部分
運(yùn)算符:&

set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3,}
print(set1 & set2)   #{1, 2, 3}

29.并集

求兩個(gè)集合的和
運(yùn)算符:|

set1 = {1, 2, 8, 4, 10}
set2 = {1, 20, 9,}
print(set1 | set2)   # {1, 2, 4, 20, 8, 9, 10}

30.差集

運(yùn)算符: -
集合1 - 集合2 :求集合1中除了集合2以外的部分

set1 = {1, 2, 8, 4, 10}
set2 = {1, 20, 9,}
print(set1 - set2)   # {8, 2, 10, 4}

31.補(bǔ)集

運(yùn)算符: ^
求兩個(gè)集合除了公共部分以外的部分

set1 = {1, 2, 8, 4, 10}
set2 = {1, 20, 9,}
print(set1 ^ set2)   # {2, 4, 8, 9, 10, 20}

類型轉(zhuǎn)換


1.整型

語(yǔ)法:int()
浮點(diǎn)數(shù)、布爾、部分字符串
去掉引號(hào)后就本身就是整數(shù),才能轉(zhuǎn)換成整型

print(int('+4'), int('-5'))

2.浮點(diǎn)數(shù)

語(yǔ)法:float()
整數(shù)、布爾、部分字符串
去掉引號(hào)本身就是一個(gè)數(shù)字的字符串才能轉(zhuǎn)換成浮點(diǎn)數(shù)

print(float('23.5'),float(+25), float(-5))

3.bool

語(yǔ)法:bool()
所有的數(shù)據(jù)都能轉(zhuǎn)換成bool類型
所有容器為空時(shí)轉(zhuǎn)換都是False,整數(shù)0才能轉(zhuǎn)換成False

print(bool(-5))
print(bool(None))

簡(jiǎn)化條件語(yǔ)句
num = 11
if num:
    print('不為0')

4.字符串

語(yǔ)法:str()
所的數(shù)據(jù)都可以轉(zhuǎn)換成字符串,也就是在數(shù)據(jù)外面加引號(hào)

print(str([1, 2, 5]),str({'name': 555, 'age': 18}))

5.列表

語(yǔ)法:list()
序列才能轉(zhuǎn)換成列表
將序列元素作為列表的元素
字典轉(zhuǎn)化成列表只是將字典的key做作為列表的元素

print(list({'a':10, 'b':20}))
print(list({'a':10, 'b':20}.items()))
# [('a', 10), ('b', 20)]

6.元祖

tuple()
將序列轉(zhuǎn)換成元祖

print(tuple({'a':10, 'b':20}))  #('a', 'b')
print(tuple({'a':10, 'b':20}.items()))  #(('a', 10), ('b', 20))

7.字典

語(yǔ)法:dict()
只有序列才能轉(zhuǎn)換成字典,要求序列的每個(gè)元素有且只有兩個(gè)元素

print(dict([('name', 'xiaoming'), ('age', 20)]))

8.集合set

語(yǔ)法:set()
序列可以轉(zhuǎn)換成集合,有去重的功能
字典轉(zhuǎn)換成集合,也只能將key作為集合的元素

print(set({'naem' : 'xiaoming', 'age': 18}))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容