Python常用對象之列表操作手冊之列表方法

Python常用對象之列表操作手冊之列表方法與運算符

約定: 示例代碼中 >>> 表示交互輸入
約定: 示例代碼中 <<< 表示交互輸出

運算符

運算符 說明 原型 (魔法方法)
in 判斷列表是否包含某個元素 __contains__(self, key) -> bool
not in 判斷列表是否不包含某個元素 __contains__(self, key) -> bool
is 判斷兩個列表是否爲同一個列表 (指向同一個地址) 內置語言實現
len 計算列表元素數 __len__(self) -> int
== 判斷兩個列表中的元素是否相同 (注意與is的區別) __eq__(self, value) -> bool
!= 判斷兩個列表中的元素是否不相同 __ne__(self, value) -> bool
+ 連接兩個列表, 返回新的副本 __add__(self, value) -> list
+= list.extend方法的簡寫形式 __iadd__(self, value) -> None
[ ] 列表索引與切片 __getitem__(self, key) -> object
< 比較列表元素

如果左邊列表的某個元素小於右邊列表相同位置的元素則返回True, 否則返回False
__lt__(self, other) -> bool
> 比較列表元素 __gt__(self, other) -> bool
<= 比較列表元素

如果右邊列表的某個元素小於左邊列表相同位置的元素則返回False, 否則返回True
__le__(self, other) -> bool
>= 比較列表元素 __ge__(self, other) -> bool
* 重複列表元素, 返回新的副本, 類似字符串的*運算符 __mul__(self, other)__ -> list


列表方法

看完我以前的文章應該已經能夠看懂原型了, 所以這裏就只簡單介紹下功能

分類 方法 功能 原型
append 添加元素 append(self, object) -> None
extend 添加集合 extend(self, iterable) -> None
insert 插入元素 insert(self, index, object) -> None
pop 彈出元素 pop(self, index=-1) -> object
remove 刪除元素 remove(self, value) -> None
count 統計元素在列表中出現的次數 count(self, value) -> int
其它 sort 排序 sort(self, key=None, reverse=False) -> None
reverse 反轉元素 reverse() -> None
clear 清空列表 clear(self) -> None
copy 淺拷貝 copy(self) -> list

如果您覺得此文章對您有所幫助, 請幫我點贊哦~



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章