02. 元組
2.1 元組的定義
-
Tuple
(元組)與列表類似,不同之處在于元組的 元素不能修改元組 表示多個元素組成的序列
元組 在
Python
開發中,有特定的應用場景
用于存儲 一串 信息,數據 之間使用
,
分隔元組用
()
定義-
元組的 索引 從
0
開始- 索引 就是數據在 元組 中的位置編號
info_tuple = ("zhangsan", 18, 1.75)
創建空元組
info_tuple = ()
元組中 只包含一個元素 時,需要 在元素后面添加逗號
info_tuple = (50, )
2.2 元組常用操作
在
ipython3
中定義一個 元組,例如:info = ()
輸入
info.
按下TAB
鍵,ipython
會提示 元組 能夠使用的函數如下:
info.count#統計計數
info.index#已知元組內容,希望知道該數據的索引
有關 元組 的 常用操作 可以參照上圖練習
2.3 循環遍歷
取值 就是從 元組 中獲取存儲在指定位置的數據
遍歷 就是 從頭到尾 依次 從 元組 中獲取數據
# for 循環內部使用的變量 in 元組
for item in info:
?
#循環內部針對元組元素進行操作
print(item)
- 在
Python
中,可以使用for
循環遍歷所有非數字型類型的變量:列表、元組、字典 以及 字符串
- 提示:在實際開發中,除非 能夠確認元組中的數據類型,否則針對元組的循環遍歷需求并不是很多
2.4 應用場景
盡管可以使用
for in
遍歷 元組-
但是在開發中,更多的應用場景是:
-
函數的 參數 和 返回值,一個函數可以接收 任意多個參數,或者 一次返回多個數據
- 有關 函數的參數 和 返回值,在后續 函數高級 給大家介紹
格式字符串,格式化字符串后面的
()
本質上就是一個元組讓列表不可以被修改,以保護數據安全
-
info = ("zhangsan", 18)
#驗證了之前在%后面傳遞的小括號就是一個元組
print("%s 的年齡是 %d" % info)
元組和列表之間的轉換
- 使用
list
函數可以把元組轉換成列表
list(元組)
- 使用
tuple
函數可以把列表轉換成元組
tuple(列表)
03. 字典
3.1 字典的定義
dictionary
(字典) 是 除列表以外Python
之中 最靈活 的數據類型-
字典同樣可以用來 存儲多個數據
- 通常用于存儲 描述一個
物體
的相關信息
- 通常用于存儲 描述一個
-
和列表的區別
列表 是 有序 的對象集合
字典 是 無序 的對象集合
字典用
{}
定義-
字典使用 鍵值對 存儲數據,鍵值對之間使用
,
分隔鍵
key
是索引值
value
是數據鍵 和 值 之間使用
:
分隔鍵必須是唯一的
值 可以取任何數據類型,但 鍵 只能使用 字符串、數字或 元組
xiaoming = {"name": "小明",
"age": 18,
"gender": True,
"height": 1.75}
#使用print()輸出內容時,輸出的順序和定義的順序是不一致的,因為字典是無序的。
3.2 字典常用操作
在
ipython3
中定義一個 字典,例如:xiaoming = {}
輸入
xiaoming.
按下TAB
鍵,ipython
會提示 字典 能夠使用的函數如下:
In [1]: xiaoming.
xiaoming.clear xiaoming.items xiaoming.setdefault
xiaoming.copy xiaoming.keys xiaoming.update#合并字典,如果被合并的字典中包含已經存在的鍵值對,會覆蓋原有的鍵值對。
xiaoming.fromkeys xiaoming.pop xiaoming.values
xiaoming.get xiaoming.popitem
有關 字典 的 常用操作 可以參照上圖練習
3.3 循環遍歷
- 遍歷 就是 依次 從 字典 中獲取所有鍵值對
# for 循環內部使用的 `key 的變量` in 字典
for k in xiaoming:
?
print("%s: %s" % (k, xiaoming[k]))
提示:在實際開發中,由于字典中每一個鍵值對保存數據的類型是不同的,所以針對字典的循環遍歷需求并不是很多
3.4 應用場景
盡管可以使用
for in
遍歷 字典-
但是在開發中,更多的應用場景是:
使用 多個鍵值對,存儲 描述一個
物體
的相關信息 —— 描述更復雜的數據信息將 多個字典 放在 一個列表 中,再進行遍歷,在循環體內部針對每一個字典進行 相同的處理
card_list = [{"name": "張三",
"qq": "12345",
"phone": "110"},
{"name": "李四",
"qq": "54321",
"phone": "10086"}
]
for card_info in card_list:
print(card_info)
04. 字符串
4.1 字符串的定義
字符串 就是 一串字符,是編程語言中表示文本的數據類型
-
在 Python 中可以使用 一對雙引號
"
或者 一對單引號'
定義一個字符串-
雖然可以使用
\"
或者\'
做字符串的轉義,但是在實際開發中:如果字符串內部需要使用
"
,可以使用'
定義字符串如果字符串內部需要使用
'
,可以使用"
定義字符串
-
可以使用 索引 獲取一個字符串中 指定位置的字符,索引計數從 0 開始
也可以使用
for
循環遍歷 字符串中每一個字符
大多數編程語言都是用
"
來定義字符串
string = "Hello Python"
?
for c in string:
print(c)
4.2 字符串的常用操作
在
ipython3
中定義一個 字符串,例如:hello_str = ""
輸入
hello_str.
按下TAB
鍵,ipython
會提示 字符串 能夠使用的 方法 如下:
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
提示:正是因為 python 內置提供的方法足夠多,才使得在開發時,能夠針對字符串進行更加靈活的操作!應對更多的開發需求!
1) 判斷類型 - 9
方法 | 說明 |
---|---|
string.isspace() | 如果 string 中只包含空格(空白字符,也包括\t,\n,\r),則返回 True |
string.isalnum() | 如果 string 至少有一個字符并且所有字符都是字母或數字則返回 True |
string.isalpha() | 如果 string 至少有一個字符并且所有字符都是字母則返回 True |
string.isdecimal() | 如果 string 只包含數字則返回 True,全角數字
|
string.isdigit() | 如果 string 只包含數字則返回 True,全角數字 、⑴ 、\u00b2
|
string.isnumeric() | 如果 string 只包含數字則返回 True,全角數字 ,漢字數字
|
string.istitle() | 如果 string 是標題化的(每個單詞的首字母大寫)則返回 True |
string.islower() | 如果 string 中包含至少一個區分大小寫的字符,并且所有這些(區分大小寫的)字符都是小寫,則返回 True |
string.isupper() | 如果 string 中包含至少一個區分大小寫的字符,并且所有這些(區分大小寫的)字符都是大寫,則返回 True |
2) 查找和替換 - 7
方法 | 說明 |
---|---|
string.startswith(str) | 檢查字符串是否是以 str 開頭,是則返回 True |
string.endswith(str) | 檢查字符串是否是以 str 結束,是則返回 True |
string.find(str, start=0, end=len(string)) | 檢測 str 是否包含在 string 中,如果 start 和 end 指定范圍,則檢查是否包含在指定范圍內,如果是則返回開始的索引值,否則返回 -1
|
string.rfind(str, start=0, end=len(string)) | 類似于 find(),不過是從右邊開始查找 |
string.index(str, start=0, end=len(string)) | 跟 find() 方法類似,不過如果 str 不在 string 會報錯 |
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) 大小寫轉換 - 5
方法 | 說明 |
---|---|
string.capitalize() | 把字符串的第一個字符大寫 |
string.title() | 把字符串的每個單詞首字母大寫 |
string.lower() | 轉換 string 中所有大寫字符為小寫 |
string.upper() | 轉換 string 中的小寫字母為大寫 |
string.swapcase() | 翻轉 string 中的大小寫 |
4) 文本對齊 - 3
方法 | 說明 |
---|---|
string.ljust(width) | 返回一個原字符串左對齊,并使用空格填充至長度 width 的新字符串 |
string.rjust(width) | 返回一個原字符串右對齊,并使用空格填充至長度 width 的新字符串 |
string.center(width) | 返回一個原字符串居中,并使用空格填充至長度 width 的新字符串 |
5) 去除空白字符 - 3
方法 | 說明 |
---|---|
string.lstrip() | 截掉 string 左邊(開始)的空白字符 |
string.rstrip() | 截掉 string 右邊(末尾)的空白字符 |
string.strip() | 截掉 string 左右兩邊的空白字符 |
6) 拆分和連接 - 5
方法 | 說明 |
---|---|
string.partition(str) | 把字符串 string 分成一個 3 元素的元組 (str前面, str, str后面) |
string.rpartition(str) | 類似于 partition() 方法,不過是從右邊開始查找 |
string.split(str="", num) | 以 str 為分隔符拆分 string,如果 num 有指定值,則僅分隔 num + 1 個子字符串,str 默認包含 '\r', '\t', '\n' 和空格 |
string.splitlines() | 按照行('\r', '\n', '\r\n')分隔,返回一個包含各行作為元素的列表 |
string.join(seq) | 以 string 作為分隔符,將 seq 中所有的元素(的字符串表示)合并為一個新的字符串 |
4.3 字符串的切片
-
切片 方法適用于 字符串、列表、元組
切片 使用 索引值 來限定范圍,從一個大的 字符串 中 切出 小的 字符串
列表 和 元組 都是 有序 的集合,都能夠 通過索引值 獲取到對應的數據
字典 是一個 無序 的集合,是使用 鍵值對 保存數據
字符串[開始索引:結束索引:步長]
注意:
-
指定的區間屬于 左閉右開 型
[開始索引, 結束索引)
=>開始索引 >= 范圍 < 結束索引
- 從
起始
位開始,到結束
位的前一位 結束(不包含結束位本身)
- 從
從頭開始,開始索引 數字可以省略,冒號不能省略
到末尾結束,結束索引 數字可以省略,冒號不能省略
步長默認為
1
,如果連續切片,數字和冒號都可以省略
索引的順序和倒序
在 Python 中不僅支持 順序索引,同時還支持 倒序索引
-
所謂倒序索引就是 從右向左 計算索引
- 最右邊的索引值是 -1,依次遞減
演練需求
- 截取從 2 ~ 5 位置 的字符串
- 截取從 2 ~
末尾
的字符串
- 截取從 2 ~
- 截取從
開始
~ 5 位置 的字符串
- 截取從
- 截取完整的字符串
- 從開始位置,每隔一個字符截取字符串
- 從索引 1 開始,每隔一個取一個
- 截取從 2 ~
末尾 - 1
的字符串
- 截取從 2 ~
- 截取字符串末尾兩個字符
- 字符串的逆序(面試題)
答案
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\. 從開始位置,每隔一個字符截取字符串
print(num_str[::2])
?
# 6\. 從索引 1 開始,每隔一個取一個
print(num_str[1::2])
?
# 倒序切片
# -1 表示倒數第一個字符
print(num_str[-1])
?
# 7\. 截取從 2 ~ `末尾 - 1` 的字符串
print(num_str[2:-1])
?
# 8\. 截取字符串末尾兩個字符
print(num_str[-2:])
?
# 9\. 字符串的逆序(面試題)
print(num_str[::-1])
05. 公共方法(對列表、元組、字典都能使用)
5.1 Python 內置函數(不用import
導入,直接可調用)
Python 包含了以下內置函數:
函數 | 描述 | 備注 |
---|---|---|
len(item) | 計算容器中元素個數 | |
del(item) | 刪除變量或變量中元素 | del 有兩種方式 |
max(item) | 返回容器中元素最大值 | 如果是字典,只針對 key 比較 |
min(item) | 返回容器中元素最小值 | 如果是字典,只針對 key 比較 |
cmp(item1, item2) | 比較兩個值,-1 小于/0 相等/1 大于 | Python 3.x 取消了 cmp 函數 |
注意
字符串 比較符合以下規則: "0" < "A" < "a"
字典不能比較大小。
5.2 切片
描述 | Python 表達式 | 結果 | 支持的數據類型 |
---|---|---|---|
切片 | "0123456789"[::-2] | "97531" | 字符串、列表、元組 |
切片 使用 索引值 來限定范圍,從一個大的 字符串 中 切出 小的 字符串
列表 和 元組 都是 有序 的集合,都能夠 通過索引值 獲取到對應的數據
字典 是一個 無序 的集合,是使用 鍵值對 保存數據
5.3 運算符
運算符 | Python 表達式 | 結果 | 描述 | 支持的數據類型 |
---|---|---|---|---|
+ | [1, 2] + [3, 4] | [1, 2, 3, 4] | 合并 | 字符串、列表、元組 |
* | ["Hi!"] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | 重復 | 字符串、列表、元組 |
in | 3 in (1, 2, 3) | True | 元素是否存在 | 字符串、列表、元組、字典 |
not in | 4 not in (1, 2, 3) | True | 元素是否不存在 | 字符串、列表、元組、字典 |
> >= == < <= | (1, 2, 3) < (2, 2, 3) | True | 元素比較 | 字符串、列表、元組 |
注意
in
在對 字典 操作時,判斷的是 字典的鍵in
和not in
被稱為 成員運算符
成員運算符
成員運算符用于 測試 序列中是否包含指定的 成員
運算符 | 描述 | 實例 |
---|---|---|
in | 如果在指定的序列中找到值返回 True,否則返回 False |
3 in (1, 2, 3) 返回 True
|
not in | 如果在指定的序列中沒有找到值返回 True,否則返回 False |
3 not in (1, 2, 3) 返回 False
|
注意:在對 字典 操作時,判斷的是 字典的鍵
5.4 完整的 for 循環語法
- 在
Python
中完整的for 循環
的語法如下:
for 變量 in 集合:
循環體代碼
else:#else后面的代碼時循環全部介紹后才會執行。
沒有通過 break 退出循環,循環結束后,會執行的代碼
應用場景
在 迭代遍歷 嵌套的數據類型時,例如 一個列表包含了多個字典
-
需求:要判斷 某一個字典中 是否存在 指定的 值
如果 存在,提示并且退出循環
如果 不存在,在 循環整體結束 后,希望 得到一個統一的提示
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)
?
# 判斷當前遍歷的字典中姓名是否為find_name
if stu_dict["name"] == find_name:
print("找到了")
?
# 如果已經找到,直接退出循環,就不需要再對后續的數據進行比較,也不會執行else后面的內容
break
?
else:
print("沒有找到")
?
print("循環結束")
以上內容來自黑馬程序員,覺得不錯,何不點個贊?