日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python?列表常用方法超詳細梳理總結_python

作者:hacker707 ? 更新時間: 2022-05-20 編程語言

列表是什么?

列表由一系列特定順序排列的元素組成,你可以創(chuàng)建包含字母表中的所有字母、數字0~9、所有家庭成員姓名的列表等等,也可以將任何東西放入列表中,其中元素之間可以沒有任何關系,鑒于列表通常包含多個元素,給列表指定一個表示復數的名稱(如names、digits或letters)是個不錯的主意 在python中,列表用方括號[ ]表示,并用逗號分隔其中的元素。

列表常用方法

1.append()

定義 append() 方法向列表末尾追加元素。 ??舉個栗子??向fruits列表添加元素

fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
print(fruits)

運行結果如下:

['apple', 'banana', 'cherry', 'orange']

2.clear()

定義 clear()方法清空列表所有元素 ??舉個栗子??清空fruits所有元素(返回空列表)

fruits = ['apple', 'banana', 'cherry', 'orange']
fruits.clear()
print(fruits)

運行結果如下:

[]

3.copy()

定義 copy()方法返回指定列表的副本(復制列表) ??舉個栗子??復制fruits列表

fruits = ['apple', 'banana', 'cherry', 'orange']
c = fruits.copy()
print(c)

運行結果如下:

['apple', 'banana', 'cherry', 'orange']

4.count()

定義 count()方法返回元素出現次數 ??舉個栗子 ?? 返回 “cherry” 在 fruits 列表中出現的次數

fruits = ['apple', 'banana', 'cherry']
number = fruits.count("cherry")
print(number)

運行結果如下:

1

5.extend()

定義 extend()方法將列表元素(或任何可迭代的元素)添加到當前列表的末尾 ??舉個栗子 ??把cars中的元素添加到fruits列表

fruits = ['apple', 'banana', 'cherry']
cars = ['Porsche', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)

運行結果如下:

['apple', 'banana', 'cherry', 'Porsche', 'BMW', 'Volvo']

6.index()

定義 index()方法返回該元素最小索引值(找不到元素會報錯) ??舉個栗子??返回“cherry”元素的最小索引值

fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)

運行結果如下:

2

7.insert()

定義 在指定位置插入元素 ??舉個栗子??將"orange"元素插入到fruits列表索引為1的位置

fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)

運行結果如下:

['apple', 'orange', 'banana', 'cherry']

8.reverse()

定義reverse() 方法反轉元素的排序順序 ??舉個栗子??反轉fruits列表

fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)

運行結果如下:

['cherry', 'banana', 'apple']

9.remove()

定義 remove() 方法具有指定值的首個元素 ??舉個栗子??刪除 fruits 列表的 “banana” 元素

fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)

運行結果如下:

['apple', 'cherry']

10.pop()

定義 pop() 刪除指定位置的元素 ??舉個栗子??刪除 fruits 列表的"banana"元素(指定該元素索引)

fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)

運行結果如下:

['apple', 'cherry']

11.sort()

定義 默認情況下,sort() 方法對列表進行升序排序 ??舉個栗子??以字母順序排序cars列表

cars = ['Porsche', 'BMW', 'Volvo']
cars.sort()
print(cars)

運行結果如下:

['BMW', 'Porsche', 'Volvo']

擴展 reverse=True 可將對列表進行降序排序。默認是 reverse=False ??舉個栗子??對cars列表進行降序排序

cars = ['Porsche', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)

運行結果如下:

['Volvo', 'Porsche', 'BMW']

以上就是列表常用的方法整理

原文鏈接:https://blog.csdn.net/xqe777/article/details/123197506

欄目分類
最近更新