8總 元祖,字典和集合

1.元祖:

什么是元祖

使用()將多個元素括起來,多個元素之間用逗號隔開
a.
是容器,可以同時存儲多個數(shù)據(jù),不可變的,有序的
不可變 ---> 不能增刪改
有序 ---> 可以通過下標獲取元素

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

tuple1 = (1, 'yue', True, [1, 2], lambda s:s*2)
print(tuple1)

注意!

-1.
如果元祖的元素只有一個的時候,必須在元素的后面加逗號

tuple2 = (100,)
print(type(tuple2))

-2.
多個數(shù)據(jù)直接用逗號隔開,表示的也是一個元祖


tuple2 = 10, 20, 'abc'
print(tuple2, type(tuple2))

2.元素的查

元祖的元素不支持增刪改
列表獲取元素的方式,元祖都支持:元祖[下標], 元祖[:], 元祖[::]
遍歷:和列表一樣

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

遍歷

for item in tuple2:
    print(item)

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

補充:獲取部分元素
可以通過相同的變量個數(shù),來一一獲取元祖中的元素

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

x, y, z = (10, 20, 30)

x, y = 10, 20

1.應用:交換兩個數(shù)的值

a = 10
b = 20

錯誤寫法
a = b # a = 20
b = a # b = 20

方法1:

 t = a   # t = 10
a = b   # a = 20
b = t   # b = 10

方法2:

a, b = b, a  # a,b = (b,a) = (20, 10)

可以通過在變量前加*來獲取部分的元素(適用于列表)

tuple2 = ('小明', 90, 89, 67, 100)
name, *score = tuple2
print(name, score)
tuple2 = (90, 89, 67, 100, '小明')
*score, name = tuple2
print(score, name)
tuple2 = ['boy', 15300022673, 90, 89, 67, 100, '小明']
sex, tel, *score, name = tuple2
print(sex, name, score)

(了解)
可以通過在列表或者元祖前加*,來展開列表中的元素

tuple3 = (1, 2, 3, 4)
print(*tuple3)

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

3.元祖的運算

+, *, ==, is, in, not in ---> 和列表一樣

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

4.len(), max(), min()

tuple3 = 10, 230, 100, 78, 34
print(len(tuple3))
print(max(tuple3))
print(min(tuple3))

6.tuple()

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

print(tuple('abhdnc'))
print(tuple([1, 23, 90]))
print(tuple(range(5)))
print(tuple({'a': 100, 'b': 200}))

7.sorted()

可以通過sorted()方法,對元祖進行排序,產(chǎn)生一個新的列表

tuple3 = 10, 230, 100, 78, 34
new = sorted(tuple3)
print(new, tuple3)

2.字典:

什么時候用容器類型的數(shù)據(jù)? ---> 需要同時保存多個數(shù)據(jù)的時候
什么時候用列表? ---> 保存的多個數(shù)據(jù)是同一類的數(shù)據(jù)(不需要區(qū)分)
什么時候用字典? ---> 保存的多個數(shù)據(jù)是不同類的數(shù)據(jù) (需要區(qū)分)

1.什么是字典(dict)

字典是一個容器類的數(shù)據(jù)類型,可以用來存儲多個數(shù)據(jù)(以鍵值對的形式存儲)??勺兊?,無序的
{key1:value1, key2:value2...}
可變 ---> 可以增刪改
無序 ---> 不能通過下標獲取值

鍵(key): 用來定位值的。要求只能是不可變的數(shù)據(jù)類型(數(shù)字,字符串,元祖...)。是唯一的
值(value): 存儲的數(shù)據(jù)。可以是任何類型的數(shù)據(jù)

person1 = ['yuting', 18, 90, 100, '1547262889']
person2 = {'name': 'yuting', 'age': 18, 'face': 90, 'score': 100, 'tel': '1547262889', 'name':'小花'}
dict1 = {10: 893, 'abc': 100, (1, 23): 'abc'}
print(person2)

dict1 = {}
print(dict1)

3.字典的增刪改查:

1.查(獲取鍵值對的value)

獲取字典的值,必須通過key來獲取

a.字典[key] ---> 獲取key對應的值
注意:key值必須是存在的,否則會報KeyError

student = {'name': '小明', 'age': 30, 'study_id': 'py001', 'sex': 'boy'}
print(student['name'])
print(student['sex'])
print(student['score'])   # KeyError: 'score'

b.字典.get(key) ---> 通過key獲取值
注意:key值不存在的時候不會報錯,結果是None

print(student.get('age'), student.get('study_id'))
print(student.get('score'))

確定key一定存在就是使用[]語法,key可能不存在的時候使用get語法

c.直接遍歷字典(推薦使用)
通過for-in遍歷字典拿到的是key值

for x in student:
print(x, student[x])

d.其他遍歷方式(了解)

直接遍歷拿到值

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

直接拿到key和value

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

2.增(添加鍵值對)

字典[key] = 值(key不存在)

car = {}
car['color'] = 'yellow'
print(car)

car['price'] = 300000
print(car)

3.修改(修改值)

字典[key] = 新值 (key存在)

car['color'] = 'red'
print(car)

4.刪 (刪除鍵值對)

a. del 字典[key] ---> 通過key刪除鍵值對

student = {'name': '小明', 'age': 30, 'study_id': 'py001', 'sex': 'boy'}
del student['age']
print(student)

b. 字典.pop(key) ---> 取出key對應的值(實質還是刪除key對應的鍵值對)

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

4.字典相關的操作:

1.字典相關運算

==: 判斷兩個字典的值是否相等
is: 判斷兩個字典的地址是否相等

in 和 not in: key in 字典 / key not in 字典 ---> 判斷key是否存在

dic1 = {'a': 1, 'b': 2}
aa = dic1
print(dic1 is aa)
print({'a': 100, 'b': 200} == {'b': 200, 'a': 100})
print({'a': 100, 'b': 200} is {'b': 200, 'a': 100})
print('abc' in {'abc': 100, 'a': 200})  # True
print('abc' in {'100': 'abc', 'a': 200})  # False

2.字典相關的函數(shù)和方法

len(字典) --> 獲取鍵值對的個數(shù)

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(len(dict1))

2.字典.clear() --> 清空字典

dict1.clear()
print(dict1)

3.字典.copy() --> 將字典中的鍵值對復制一份產(chǎn)生一個新的字典

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict2 = dict1.copy()
print(dict2, dict1 is dict2)

4.dict.fromkeys(序列, 值) --> 創(chuàng)建一個字典,將序列中的每個元素作為key,值作為value

dict3 = dict.fromkeys('xyz', 100)
print(dict3)
dict3 = dict.fromkeys(['aa', 'bb', 'cc'], (1, 2))
print(dict3)

字典.get(key) --> key不存在取None
字典.get(key,默認值) --> key不存在取默認值

student = {}
print(student.get('name'))
print(student.get('name', '無名'))

字典.values() --> 返回所有值對應的序列
字典.keys() --> 返回所有鍵對應的序列
字典.items() --> 將鍵值對轉換成元祖,作為一個序列的元素
注意:返回的都不是列表,是其他類型的序列

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
items = list(dict1.items())
print(items, type(items))
print(dict1.items(), type(dict1.items()))

字典.setdefault(key) --> 添加鍵值對,鍵是key,值是None
字典.setdefault(key,value) --> 添加鍵值對,鍵是key,值是value
注意:key存在的時候,對字典不會有任何操作(不會修改key對應的值)

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict1.setdefault('aa')
print(dict1)

8.字典1.update(字典2) --> 使用字典2中鍵值對去更新字典1。(已經(jīng)存在的key就更新,不存在就添加)

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 200, 'c': 100}
dict1.update(dict2)
print(dict1)

5.集合:

1.什么是集合(set)

容器,可以同時存儲多個數(shù)據(jù),可變的,無序的,元素是唯一的
可變 --> 增刪改
無序 --> 不能通過下標獲取元素
唯一 --> 自帶去重的功能
{元素1, 元素2...}

元素:只能是不可變的數(shù)據(jù)

set1 = {10, 20, 'abc', (10, 200), 10}
print(set1)   # {(10, 200), 10, 20, 'abc'}

set2 = {} # 這個是空的字典

2.集合的增刪改查

a.查(獲取元素)

集合不能單獨的獲取一個元素,也不能切片,只能通過for-in來遍歷

for x in set1:
    print(x)

b.增(添加元素)

集合.add(元素) --> 在集合中添加一個元素

set1 = {1, 2, 3}
set1.add(4)
print(set1)

集合1.update(序列) --> 將序列中的元素添加到集合1中

set1.update({'a', 'b'})
print(set1)

set1.update('0987')
print(set1)

set1.update(['abc', 'aaa'])
print(set1)

set1.update({'name': 1, 'age': 18})   # 字典只添加key
print(set1)

3.刪(刪除元素)

集合.remove(元素) --> 刪除指定的元素

set1.remove(1)
print(set1)

4.改(集合不能改)

6.集合相關的運算:

集合相關的運算: 是否包含,交集、并集、差集、補集

1.包含

集合1 >= 集合2 ---> 判斷集合1之中是否包含集合2
集合2 <= 集合2 ---> 判斷集合2之中是否包含集合1
···
set1 = {1, 2, 3, 4, 5, 10}
set2 = {3, 4, 1}
print(set1 >= set2)
···

2.交集 -> &

& --> 求兩個集合公共的部分
···
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3, 10, 20}
print(set1 & set2)
···

3.求并集

| --> 求兩個集合的和

print(set1 | set2)

4.求差集

集合1-集合2 --> 求集合1中除了集合2以外的部分

print(set1 - set2)

5.求補集

^ --> 求兩個集合除了公共部分以外的部分

print(set1 ^ set2)

7.類型的轉換:

1.整型

int()
浮點數(shù)、布爾、部分字符串可以轉換成整型。

只有去掉引號后本身就是一個整數(shù)的字符串才能轉換成整型

print(int('34'))
print(int('+45'))
print(int('-90'))
print(int('34.5'))  # ValueError

2.浮點數(shù)

整數(shù),布爾,部分字符串可以轉換成浮點數(shù)

去掉的引號,本身就是一個數(shù)字的字符串才能轉換成浮點數(shù)

print(float(100))   # 100.0
print(float(True))
print(float('34.90'))
print(float('100'))

3.布爾

所有的數(shù)據(jù)都可以抓換成布爾值

為空為0的值轉換成False, 其他的數(shù)據(jù)都轉換成True

print(bool('abchd'))  # True
print(bool('False'))  # True
print(bool(''))  # False
print(bool([1, 2, 3]))  # True
print(bool([]))    # False
print(bool({'a': 1}))  # True
print(bool({}))  # False
print(bool(()))
print(bool(0.00))
print(bool(None))
num = 100
if num == 0:
    print('是0')

if not num:
    print('是0')

names = [23]
if names:
    print('不是空')
else:
    print('是空')


num = 230
if num % 2:
    print('是奇數(shù)')
else:
    print('是偶數(shù)')

4.字符串

str()
所有的數(shù)據(jù)都可以轉換成字符串
數(shù)據(jù)轉換成字符串,就是在數(shù)據(jù)的最外面加引號

print([str(100)])
print([str(True)])
print([str([1, 2, 3])])
print([str({'a': 1, 'b': 2})])
print([str(lambda x: x*2)])
list_str = str([1, 2, 3])
print(len(list_str))

5.列表

list()
序列才能轉換成列表。
將序列中的元素作為列表的元素。字典轉換成列表,將字典的key作為列表的元素

print(list('styui'))
print(list((23, 45, 'ac')))
print(list({'a': 100, 'b': 89}))
print(list({'a': 100, 'b': 89}.items()))

6.元祖(和列表一樣)

tuple()
只能將序列轉換成元祖

print(tuple('ancbd'))
print(tuple({'a': 100, 'b': 89}))

7.字典

dict()
序列的每個元素有兩個元素的數(shù)據(jù)才能轉換成字典

list1 = [(1, 2)]
print(dict(list1))
tuple1 = ((1, 8), {'a', 'b'})
print(dict(tuple1))

8.集合

set()
序列可以轉換成集合,有去重的功能

print(set([1, 1, 90, 3, 10, 10]))
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容