Python的公共方法

2021-10-09 10:38:27 字數 1787 閱讀 3971

完整的 for 迴圈語法

python 包含了以下內建函式:

函式描述

備註len(item)

計算容器中元素個數

del(item)

刪除變數

del 有兩種方式

max(item)

返回容器中元素最大值

如果是字典,只針對 key 比較

min(item)

返回容器中元素最小值

如果是字典,只針對 key 比較

cmp(item1, item2)

比較兩個值,-1 小於/0 相等/1 大於

python 3.x 取消了 cmp 函式

注意

描述python 表示式

結果支援的資料型別

切片「0123456789」[::-2]

「97531」

字串、列表、元組

運算子python 表示式

結果描述

支援的資料型別

+[1, 2] + [3, 4]

[1, 2, 3, 4]

合併字串、列表、元組

*[「hi!」] * 4

[『hi!』, 『hi!』, 『hi!』, 『hi!』]

重複字串、列表、元組

in3 in (1, 2, 3)

true

元素是否存在

字串、列表、元組、字典

not in

4 not in (1, 2, 3)

true

元素是否不存在

字串、列表、元組、字典

> >= == < <=

(1, 2, 3) < (2, 2, 3)

true

元素比較

字串、列表、元組

注意

成員運算子

成員運算子用於測試序列中是否包含指定的成員

運算子描述例項

in如果在指定的序列中找到值返回 true,否則返回 false

3 in (1, 2, 3)返回true

not in

如果在指定的序列中沒有找到值返回 true,否則返回 false

3 not in (1, 2, 3)返回false

注意:在對字典操作時,判斷的是字典的鍵

for 變數 in 集合:

迴圈體**

else

: 沒有通過 break 退出迴圈,迴圈結束後,會執行的**

應用場景

students =[,

,]find_name =

"阿土"

for stu_dict in students:

print

(stu_dict)

# 判斷當前遍歷的字典中姓名是否為find_name

if stu_dict[

"name"

]== find_name:

print

("找到了"

)# 如果已經找到,直接退出迴圈,就不需要再對後續的資料進行比較

break

else

:print

("沒有找到"

)print

("迴圈結束"

)

python 公共方法

運算子 python 表示式 結果描述 支援的資料型別 1,2 3,4 1,2,3,4 合併字串 列表 元組 hi 4 hi hi hi hi 複製字串 列表 元組 in3 in 1,2,3 true 元素是否存在 字串 列表 元組 字典 not in 4 not in 1,2,3 true 元素是...

python 公共方法

1.計算長度 value wangdianchao 計算字元個數 長度 number len value print number 2.索引取值 value wangdianchao 獲取value 0 位置的字元 number value 0 print number value wangdian...

python 容器型別公共方法

1.python內建函式 函式描述 備註len item 計算容器中元素的個數 del item 刪除變數 del 有兩種方式 max item 返回容器中元素最大值 如果是字典,只針對key比較 min item 返回容器中元素最小值 如果是字典,只針對key比較 2.運算子 運算子python表...