python集合加个逗号_8.Python集合与字符串
高級(jí)變量類型
目標(biāo)
列表
元組
字典
字符串
公共方法
變量高級(jí)
知識(shí)點(diǎn)回顧
Python 中數(shù)據(jù)類型可以分為 數(shù)字型 和 非數(shù)字型
數(shù)字型
整型 (int)
浮點(diǎn)型(float)
布爾型(bool)
真 True 非 0 數(shù) —— 非零即真
假 False 0
復(fù)數(shù)型 (complex)
主要用于科學(xué)計(jì)算,例如:平面場問題、波動(dòng)問題、電感電容等問題
非數(shù)字型
字符串
列表
元組
字典
在 Python 中,所有 非數(shù)字型變量 都支持以下特點(diǎn):
都是一個(gè) 序列 sequence,也可以理解為 容器
取值 []
遍歷 for in
計(jì)算長度、最大/最小值、比較、刪除
鏈接 + 和 重復(fù) *
切片
01. 列表
1.1 列表的定義
List(列表) 是 Python 中使用 最頻繁 的數(shù)據(jù)類型,在其他語言中通常叫做 數(shù)組
專門用于存儲(chǔ) 一串 信息
列表用 [] 定義,數(shù)據(jù) 之間使用 , 分隔
列表的 索引 從 0 開始
索引 就是數(shù)據(jù)在 列表 中的位置編號(hào),索引 又可以被稱為 下標(biāo)
注意:從列表中取值時(shí),如果 超出索引范圍,程序會(huì)報(bào)錯(cuò)
name_list = ["zhangsan", "lisi", "wangwu"]
image
1.2 列表常用操作
在 ipython3 中定義一個(gè) 列表,例如:name_list = []
輸入 name_list. 按下 TAB 鍵,ipython 會(huì)提示 列表 能夠使用的 方法 如下:
In [1]: name_list.
name_list.append name_list.count name_list.insert name_list.reverse
name_list.clear name_list.extend name_list.pop name_list.sort
name_list.copy name_list.index name_list.remove
序號(hào)
分類
關(guān)鍵字 / 函數(shù) / 方法
說明
1
增加
列表.insert(索引, 數(shù)據(jù))
在指定位置插入數(shù)據(jù)
列表.append(數(shù)據(jù))
在末尾追加數(shù)據(jù)
列表.extend(列表2)
將列表2 的數(shù)據(jù)追加到列表
2
修改
列表[索引] = 數(shù)據(jù)
修改指定索引的數(shù)據(jù)
3
刪除
del 列表[索引]
刪除指定索引的數(shù)據(jù)
列表.remove[數(shù)據(jù)]
刪除第一個(gè)出現(xiàn)的指定數(shù)據(jù)
列表.pop
刪除末尾數(shù)據(jù)
列表.pop(索引)
刪除指定索引數(shù)據(jù)
列表.clear
清空列表
4
統(tǒng)計(jì)
len(列表)
列表長度
列表.count(數(shù)據(jù))
數(shù)據(jù)在列表中出現(xiàn)的次數(shù)
5
排序
列表.sort()
升序排序
列表.sort(reverse=True)
降序排序
列表.reverse()
逆序、反轉(zhuǎn)
del 關(guān)鍵字(科普)
使用 del 關(guān)鍵字(delete) 同樣可以刪除列表中元素
del 關(guān)鍵字本質(zhì)上是用來 將一個(gè)變量從內(nèi)存中刪除的
如果使用 del 關(guān)鍵字將變量從內(nèi)存中刪除,后續(xù)的代碼就不能再使用這個(gè)變量了
del name_list[1]
在日常開發(fā)中,要從列表刪除數(shù)據(jù),建議 使用列表提供的方法
關(guān)鍵字、函數(shù)和方法(科普)
關(guān)鍵字 是 Python 內(nèi)置的、具有特殊意義的標(biāo)識(shí)符
In [1]: import keyword
In [2]: print(keyword.kwlist)
In [3]: print(len(keyword.kwlist))
關(guān)鍵字后面不需要使用括號(hào)
函數(shù) 封裝了獨(dú)立功能,可以直接調(diào)用
函數(shù)名(參數(shù))
函數(shù)需要死記硬背
方法 和函數(shù)類似,同樣是封裝了獨(dú)立的功能
方法 需要通過 對(duì)象 來調(diào)用,表示針對(duì)這個(gè) 對(duì)象 要做的操作
對(duì)象.方法名(參數(shù))
在變量后面輸入 .,然后選擇針對(duì)這個(gè)變量要執(zhí)行的操作,記憶起來比函數(shù)要簡單很多
1.3 循環(huán)遍歷
遍歷 就是 從頭到尾 依次 從 列表 中獲取數(shù)據(jù)
在 循環(huán)體內(nèi)部 針對(duì) 每一個(gè)元素,執(zhí)行相同的操作
在 Python 中為了提高列表的遍歷效率,專門提供的 迭代 iteration 遍歷
使用 for 就能夠?qū)崿F(xiàn)迭代遍歷
# for 循環(huán)內(nèi)部使用的變量 in 列表
for name in name_list:
循環(huán)內(nèi)部針對(duì)列表元素進(jìn)行操作
print(name)
image
1.4 應(yīng)用場景
盡管 Python 的 列表 中可以 存儲(chǔ)不同類型的數(shù)據(jù)
但是在開發(fā)中,更多的應(yīng)用場景是
列表 存儲(chǔ)相同類型的數(shù)據(jù)
通過 迭代遍歷,在循環(huán)體內(nèi)部,針對(duì)列表中的每一項(xiàng)元素,執(zhí)行相同的操作
02. 元組
2.1 元組的定義
Tuple(元組)與列表類似,不同之處在于元組的 元素不能修改
元組 表示多個(gè)元素組成的序列
元組 在 Python 開發(fā)中,有特定的應(yīng)用場景
用于存儲(chǔ) 一串 信息,數(shù)據(jù) 之間使用 , 分隔
元組用 () 定義
元組的 索引 從 0 開始
索引 就是數(shù)據(jù)在 元組 中的位置編號(hào)
info_tuple = ("zhangsan", 18, 1.75)
創(chuàng)建空元組
info_tuple = ()
元組中 只包含一個(gè)元素 時(shí),需要 在元素后面添加逗號(hào)
info_tuple = (50, )
image
2.2 元組常用操作
在 ipython3 中定義一個(gè) 元組,例如:info = ()
輸入 info. 按下 TAB 鍵,ipython 會(huì)提示 元組 能夠使用的函數(shù)如下:
info.count info.index
有關(guān) 元組 的 常用操作 可以參照上圖練習(xí)
2.3 循環(huán)遍歷
取值 就是從 元組 中獲取存儲(chǔ)在指定位置的數(shù)據(jù)
遍歷 就是 從頭到尾 依次 從 元組 中獲取數(shù)據(jù)
# for 循環(huán)內(nèi)部使用的變量 in 元組
for item in info:
循環(huán)內(nèi)部針對(duì)元組元素進(jìn)行操作
print(item)
在 Python 中,可以使用 for 循環(huán)遍歷所有非數(shù)字型類型的變量:列表、元組、字典 以及 字符串
提示:在實(shí)際開發(fā)中,除非 能夠確認(rèn)元組中的數(shù)據(jù)類型,否則針對(duì)元組的循環(huán)遍歷需求并不是很多
2.4 應(yīng)用場景
盡管可以使用 for in 遍歷 元組
但是在開發(fā)中,更多的應(yīng)用場景是:
函數(shù)的 參數(shù) 和 返回值,一個(gè)函數(shù)可以接收 任意多個(gè)參數(shù),或者 一次返回多個(gè)數(shù)據(jù)
有關(guān) 函數(shù)的參數(shù) 和 返回值,在后續(xù) 函數(shù)高級(jí) 給大家介紹
格式字符串,格式化字符串后面的 () 本質(zhì)上就是一個(gè)元組
讓列表不可以被修改,以保護(hù)數(shù)據(jù)安全
info = ("zhangsan", 18)
print("%s 的年齡是 %d" % info)
元組和列表之間的轉(zhuǎn)換
使用 list 函數(shù)可以把元組轉(zhuǎn)換成列表
list(元組)
使用 tuple 函數(shù)可以把列表轉(zhuǎn)換成元組
tuple(列表)
03. 字典
3.1 字典的定義
dictionary(字典) 是 除列表以外 Python 之中 最靈活 的數(shù)據(jù)類型
字典同樣可以用來 存儲(chǔ)多個(gè)數(shù)據(jù)
通常用于存儲(chǔ) 描述一個(gè) 物體 的相關(guān)信息
和列表的區(qū)別
列表 是 有序 的對(duì)象集合
字典 是 無序 的對(duì)象集合
字典用 {} 定義
字典使用 鍵值對(duì) 存儲(chǔ)數(shù)據(jù),鍵值對(duì)之間使用 , 分隔
鍵 key 是索引
值 value 是數(shù)據(jù)
鍵 和 值 之間使用 : 分隔
鍵必須是唯一的
值 可以取任何數(shù)據(jù)類型,但 鍵 只能使用 字符串、數(shù)字或 元組
xiaoming = {"name": "小明",
"age": 18,
"gender": True,
"height": 1.75}
image
3.2 字典常用操作
2、查詢
由于字典是無序的,故要獲取字典的值,必須通過key來獲取;
####### a、字典[key]——》獲取key值對(duì)應(yīng)的值
注意:key值必須是存在的,否則會(huì)報(bào)KeyError
student={'name':'alice','age':12,'sex':'boy'}
print(student['name']) #alice
print(student['sex']) #boy
print(student['score']) #KeyError: 'score'
b、字典.get(key)——>通過key獲取值
注意:key值不存在的不會(huì)報(bào)錯(cuò),結(jié)果是none
某個(gè)key值肯定存在的時(shí)候用a型,key值可能不存在的時(shí)候用b型;
print(student.get('score')) #None
c、直接遍歷字典(推薦使用)
通過for-in遍歷字典拿到的是key值
for x in student:
print(student[x])
d、其他遍歷字典
3、增(增加鍵值對(duì))
語法:字典[key]=值 key必須是在字典中不存在的
student['score']=98
print(student) #{'name': 'alice', 'age': 12, 'sex': 'boy', 'score': 98}
4、改(修改值,非key)
語法: 字典[key]=值 key必須是在字典中存在的
student['name']='harry'
print(student) #{'name': 'harry', 'age': 12, 'sex': 'boy', 'score': 98}
5、刪(刪除鍵值對(duì))
a、語法: del 字典[key] 刪除字典中某個(gè)鍵值對(duì)
del student['sex']
print(student) #{'name': 'harry', 'age': 12, 'score': 98}
b、語法: 字典.pop(key) 實(shí)質(zhì)是從字典中取走某個(gè)鍵值對(duì),非刪除
new_age=student.pop('age')
print(student,new_age) #{'name': 'harry', 'score': 98} 12 age鍵值對(duì)從字典中已取走,但還存在,故能獲取
(二)字典相關(guān)操作
1、字典相關(guān)運(yùn)算
== 判斷兩個(gè)字典的值是否相等
is 判斷兩個(gè)字典的地址是否相等
in 和 not in 判斷字典中是否包含某個(gè)鍵值(key),非值(value)
dic1 = {'a': 1, 'b': 2}
aa = dic1
print(dic1 is aa) #True
print({'a': 100, 'b': 200} == {'b': 200, 'a': 100}) #True
print({'a': 100, 'b': 200} is {'b': 200, 'a': 100}) #False
print('abc' in {'abc': 100, 'a': 200}) # True
print('abc' in {'100': 'abc', 'a': 200}) # False
(三)字典的函數(shù)和方法
1、 len(字典)--> 獲取鍵值對(duì)的個(gè)數(shù)
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(len(dict1))#4
2、字典.clear()--> 清空字典
dict1.clear()
print(dict1)#{}
3、字典.copy()--> 將字典中的鍵值對(duì)復(fù)制一份產(chǎn)生一個(gè)新的字典
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict2 = dict1.copy()
print(dict2, dict1 is dict2)#{'a': 1, 'b': 2, 'c': 3, 'd': 4} False
####### 值相同,地址不同
4、dict.fromkeys(序列,值)--> 創(chuàng)建一個(gè)字典,將序列中的每個(gè)元素作為key,值作為value
Python 字典 fromkeys() 函數(shù)用于創(chuàng)建一個(gè)新字典,以序列seq中元素做字典的鍵,值value為字典所有鍵對(duì)應(yīng)的初始值。
dict3 = dict.fromkeys('xyz', 100)
print(dict3)#{'x': 100, 'y': 100, 'z': 100}
dict3 = dict.fromkeys(['aa', 'bb', 'cc'], (1, 2))
print(dict3)#{'aa': (1, 2), 'bb': (1, 2), 'cc': (1, 2)}
5、get方法
字典.get(key)
字典.get(key,默認(rèn)值)
返回指定鍵key的值,如果值不在字典中則返回None
student = {}
student.get('name','xm') #字典.get()是訪問、獲取、查詢某個(gè)鍵,而非創(chuàng)建
print(student,type(student)) #{}
print(student.get('name','xm'))#xm 字典.get()是訪問、獲取、查詢某個(gè)鍵,返回指定鍵key的值
student.setdefault('sex','boy')#字典.setdefault()是創(chuàng)建新鍵
print(student,type(student)) #{'sex': 'boy'}
print(student.get('name'))#None
print(student.get('name', '無名'))#無名
6、key、value、items方法
字典.keys() -->返回所有鍵對(duì)應(yīng)的序列
字典.values()-->返回所有值對(duì)應(yīng)的序列
字典.items()-->將每個(gè)鍵值對(duì)轉(zhuǎn)換成元祖,作為一個(gè)序列的元素
注意:返回的都不是列表,是其他類型的序列
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(dict1.keys(),dict1.values(),sep='====')#dict_keys(['a', 'b', 'c', 'd'])====dict_values([1, 2, 3, 4])
items = list(dict1.items())
print(items, type(items)) #[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
print(dict1.items(), type(dict1.items())) #dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
7、setdefault方法
字典.setdefault(key)
字典.setdefault(key,value)
和get()類似, 如果鍵不存在于字典中,將會(huì)添加鍵key并將值設(shè)為None或者value;
如果鍵存在,不會(huì)對(duì)字典進(jìn)行任何操作(key和value均不改變);
注意:語法-字典.get()是訪問字典某鍵,語法-字典.setdefault()是創(chuàng)建某鍵;
dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
dict1.setdefault('aa')
print(dict1)#{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'aa': None}
8、update方法
字典1.update(字典2)——》把字典2的鍵值對(duì)更新到字典1里,不存在的鍵值對(duì)則進(jìn)行添加;
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 200, 'c': 100}
dict1.update(dict2)
print(dict1) #{'a': 1, 'b': 200, 'c': 100}
04. 字符串
4.1 字符串的定義
字符串 就是 一串字符,是編程語言中表示文本的數(shù)據(jù)類型
在 Python 中可以使用 一對(duì)雙引號(hào) " 或者 一對(duì)單引號(hào) ' 定義一個(gè)字符串
雖然可以使用 \" 或者 \' 做字符串的轉(zhuǎn)義,但是在實(shí)際開發(fā)中:
如果字符串內(nèi)部需要使用 ",可以使用 ' 定義字符串
如果字符串內(nèi)部需要使用 ',可以使用 " 定義字符串
可以使用 索引 獲取一個(gè)字符串中 指定位置的字符,索引計(jì)數(shù)從 0 開始
也可以使用 for 循環(huán)遍歷 字符串中每一個(gè)字符
大多數(shù)編程語言都是用 " 來定義字符串
string = "Hello Python"
for c in string:
print(c)
image
4.2 字符串的常用操作
在 ipython3 中定義一個(gè) 字符串,例如:hello_str = ""
輸入 hello_str. 按下 TAB 鍵,ipython 會(huì)提示 字符串 能夠使用的 方法 如下:
In [1]: hello_str.
hello_str.capitalize hello_str.isidentifier hello_str.rindex
hello_str.casefold hello_str.islower hello_str.rjust
hello_str.center hello_str.isnumeric hello_str.rpartition
hello_str.count hello_str.isprintable hello_str.rsplit
hello_str.encode hello_str.isspace hello_str.rstrip
hello_str.endswith hello_str.istitle hello_str.split
hello_str.expandtabs hello_str.isupper hello_str.splitlines
hello_str.find hello_str.join hello_str.startswith
hello_str.format hello_str.ljust hello_str.strip
hello_str.format_map hello_str.lower hello_str.swapcase
hello_str.index hello_str.lstrip hello_str.title
hello_str.isalnum hello_str.maketrans hello_str.translate
hello_str.isalpha hello_str.partition hello_str.upper
hello_str.isdecimal hello_str.replace hello_str.zfill
hello_str.isdigit hello_str.rfind
提示:正是因?yàn)?python 內(nèi)置提供的方法足夠多,才使得在開發(fā)時(shí),能夠針對(duì)字符串進(jìn)行更加靈活的操作!應(yīng)對(duì)更多的開發(fā)需求!
1) 判斷類型 - 9
方法
說明
string.isspace()
如果 string 中只包含空格,則返回 True
string.isalnum()
如果 string 至少有一個(gè)字符并且所有字符都是字母或數(shù)字則返回 True
string.isalpha()
如果 string 至少有一個(gè)字符并且所有字符都是字母則返回 True
string.isdecimal()
如果 string 只包含數(shù)字則返回 True,全角數(shù)字
string.isdigit()
如果 string 只包含數(shù)字則返回 True,全角數(shù)字、⑴、\u00b2
string.isnumeric()
如果 string 只包含數(shù)字則返回 True,全角數(shù)字,漢字?jǐn)?shù)字
string.istitle()
如果 string 是標(biāo)題化的(每個(gè)單詞的首字母大寫)則返回 True
string.islower()
如果 string 中包含至少一個(gè)區(qū)分大小寫的字符,并且所有這些(區(qū)分大小寫的)字符都是小寫,則返回 True
string.isupper()
如果 string 中包含至少一個(gè)區(qū)分大小寫的字符,并且所有這些(區(qū)分大小寫的)字符都是大寫,則返回 True
2) 查找和替換 - 7
方法
說明
string.startswith(str)
檢查字符串是否是以 str 開頭,是則返回 True
string.endswith(str)
檢查字符串是否是以 str 結(jié)束,是則返回 True
string.find(str, start=0, end=len(string))
檢測 str 是否包含在 string 中,如果 start 和 end 指定范圍,則檢查是否包含在指定范圍內(nèi),如果是返回開始的索引值,否則返回 -1
string.rfind(str, start=0, end=len(string))
類似于 find(),不過是從右邊開始查找
string.index(str, start=0, end=len(string))
跟 find() 方法類似,不過如果 str 不在 string 會(huì)報(bào)錯(cuò)
string.rindex(str, start=0, end=len(string))
類似于 index(),不過是從右邊開始
string.replace(old_str, new_str, num=string.count(old))
把 string 中的 old_str 替換成 new_str,如果 num 指定,則替換不超過 num 次
3) 大小寫轉(zhuǎn)換 - 5
方法
說明
string.capitalize()
把字符串的第一個(gè)字符大寫
string.title()
把字符串的每個(gè)單詞首字母大寫
string.lower()
轉(zhuǎn)換 string 中所有大寫字符為小寫
string.upper()
轉(zhuǎn)換 string 中的小寫字母為大寫
string.swapcase()
翻轉(zhuǎn) string 中的大小寫
4) 文本對(duì)齊 - 3
方法
說明
string.ljust(width)
返回一個(gè)原字符串左對(duì)齊,并使用空格填充至長度 width 的新字符串
string.rjust(width)
返回一個(gè)原字符串右對(duì)齊,并使用空格填充至長度 width 的新字符串
string.center(width)
返回一個(gè)原字符串居中,并使用空格填充至長度 width 的新字符串
5) 去除空白字符 - 3
方法
說明
string.lstrip()
截掉 string 左邊(開始)的空白字符
string.rstrip()
截掉 string 右邊(末尾)的空白字符
string.strip()
截掉 string 左右兩邊的空白字符
6) 拆分和連接 - 5
方法
說明
string.partition(str)
把字符串 string 分成一個(gè) 3 元素的元組 (str前面, str, str后面)
string.rpartition(str)
類似于 partition() 方法,不過是從右邊開始查找
string.split(str="", num)
以 str 為分隔符拆分 string,如果 num 有指定值,則僅分隔 num + 1 個(gè)子字符串,str 默認(rèn)包含 '\r', '\t', '\n' 和空格
string.splitlines()
按照行('\r', '\n', '\r\n')分隔,返回一個(gè)包含各行作為元素的列表
string.join(seq)
以 string 作為分隔符,將 seq 中所有的元素(的字符串表示)合并為一個(gè)新的字符串
4.3 字符串的切片
切片 方法適用于 字符串、列表、元組
切片 使用 索引值 來限定范圍,從一個(gè)大的 字符串 中 切出 小的 字符串
列表 和 元組 都是 有序 的集合,都能夠 通過索引值 獲取到對(duì)應(yīng)的數(shù)據(jù)
字典 是一個(gè) 無序 的集合,是使用 鍵值對(duì) 保存數(shù)據(jù)
image
字符串[開始索引:結(jié)束索引:步長]
注意:
指定的區(qū)間屬于 左閉右開 型 [開始索引, 結(jié)束索引) => 開始索引 >= 范圍 < 結(jié)束索引
從 起始 位開始,到 結(jié)束位的前一位 結(jié)束(不包含結(jié)束位本身)
從頭開始,開始索引 數(shù)字可以省略,冒號(hào)不能省略
到末尾結(jié)束,結(jié)束索引 數(shù)字可以省略,冒號(hào)不能省略
步長默認(rèn)為 1,如果連續(xù)切片,數(shù)字和冒號(hào)都可以省略
索引的順序和倒序
在 Python 中不僅支持 順序索引,同時(shí)還支持 倒序索引
所謂倒序索引就是 從右向左 計(jì)算索引
最右邊的索引值是 -1,依次遞減
演練需求
截取從 2 ~ 5 位置 的字符串
截取從 2 ~ 末尾 的字符串
截取從 開始 ~ 5 位置 的字符串
截取完整的字符串
從開始位置,每隔一個(gè)字符截取字符串
從索引 1 開始,每隔一個(gè)取一個(gè)
截取從 2 ~ 末尾 - 1 的字符串
截取字符串末尾兩個(gè)字符
字符串的逆序(面試題)
答案
num_str = "0123456789"
# 1\. 截取從 2 ~ 5 位置 的字符串
print(num_str[2:6])
# 2\. 截取從 2 ~ `末尾` 的字符串
print(num_str[2:])
# 3\. 截取從 `開始` ~ 5 位置 的字符串
print(num_str[:6])
# 4\. 截取完整的字符串
print(num_str[:])
# 5\. 從開始位置,每隔一個(gè)字符截取字符串
print(num_str[::2])
# 6\. 從索引 1 開始,每隔一個(gè)取一個(gè)
print(num_str[1::2])
# 倒序切片
# -1 表示倒數(shù)第一個(gè)字符
print(num_str[-1])
# 7\. 截取從 2 ~ `末尾 - 1` 的字符串
print(num_str[2:-1])
# 8\. 截取字符串末尾兩個(gè)字符
print(num_str[-2:])
# 9\. 字符串的逆序(面試題)
print(num_str[::-1])
05. 公共方法
5.1 Python 內(nèi)置函數(shù)
Python 包含了以下內(nèi)置函數(shù):
函數(shù)
描述
備注
len(item)
計(jì)算容器中元素個(gè)數(shù)
del(item)
刪除變量
del 有兩種方式
max(item)
返回容器中元素最大值
如果是字典,只針對(duì) key 比較
min(item)
返回容器中元素最小值
如果是字典,只針對(duì) key 比較
cmp(item1, item2)
比較兩個(gè)值,-1 小于/0 相等/1 大于
Python 3.x 取消了 cmp 函數(shù)
注意
字符串 比較符合以下規(guī)則: "0" < "A" < "a"
5.2 切片
| 描述 | Python 表達(dá)式 | 結(jié)果 | 支持的數(shù)據(jù)類型 |
| :---: | --- | --- | --- | --- |
| 切片 | "0123456789"[::-2] | "97531" | 字符串、列表、元組 |
切片 使用 索引值 來限定范圍,從一個(gè)大的 字符串 中 切出 小的 字符串
列表 和 元組 都是 有序 的集合,都能夠 通過索引值 獲取到對(duì)應(yīng)的數(shù)據(jù)
字典 是一個(gè) 無序 的集合,是使用 鍵值對(duì) 保存數(shù)據(jù)
5.3 運(yùn)算符
運(yùn)算符
Python 表達(dá)式
結(jié)果
描述
支持的數(shù)據(jù)類型
+
[1, 2] + [3, 4]
[1, 2, 3, 4]
合并
字符串、列表、元組
*
["Hi!"] * 4
['Hi!', 'Hi!', 'Hi!', 'Hi!']
重復(fù)
字符串、列表、元組
in
3 in (1, 2, 3)
True
元素是否存在
字符串、列表、元組、字典
not in
4 not in (1, 2, 3)
True
元素是否不存在
字符串、列表、元組、字典
> >= == < <=
(1, 2, 3) < (2, 2, 3)
True
元素比較
字符串、列表、元組
注意
in 在對(duì) 字典 操作時(shí),判斷的是 字典的鍵
in 和 not in 被稱為 成員運(yùn)算符
成員運(yùn)算符
成員運(yùn)算符用于 測試 序列中是否包含指定的 成員
運(yùn)算符
描述
實(shí)例
in
如果在指定的序列中找到值返回 True,否則返回 False
3 in (1, 2, 3) 返回 True
not in
如果在指定的序列中沒有找到值返回 True,否則返回 False
3 not in (1, 2, 3) 返回 False
注意:在對(duì) 字典 操作時(shí),判斷的是 字典的鍵
5.4 完整的 for 循環(huán)語法
在 Python 中完整的 for 循環(huán) 的語法如下:
for 變量 in 集合:
循環(huán)體代碼
else:
沒有通過 break 退出循環(huán),循環(huán)結(jié)束后,會(huì)執(zhí)行的代碼
應(yīng)用場景
在 迭代遍歷 嵌套的數(shù)據(jù)類型時(shí),例如 一個(gè)列表包含了多個(gè)字典
需求:要判斷 某一個(gè)字典中 是否存在 指定的 值
如果 存在,提示并且退出循環(huán)
如果 不存在,在 循環(huán)整體結(jié)束 后,希望 得到一個(gè)統(tǒng)一的提示
students = [
{"name": "阿土",
"age": 20,
"gender": True,
"height": 1.7,
"weight": 75.0},
{"name": "小美",
"age": 19,
"gender": False,
"height": 1.6,
"weight": 45.0},
]
find_name = "阿土"
for stu_dict in students:
print(stu_dict)
# 判斷當(dāng)前遍歷的字典中姓名是否為find_name
if stu_dict["name"] == find_name:
print("找到了")
# 如果已經(jīng)找到,直接退出循環(huán),就不需要再對(duì)后續(xù)的數(shù)據(jù)進(jìn)行比較
break
else:
print("沒有找到")
print("循環(huán)結(jié)束")
總結(jié)
以上是生活随笔為你收集整理的python集合加个逗号_8.Python集合与字符串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: silverlight 打开html_在
- 下一篇: asp绑定gridview属性_理解AS