python中list的各種方法使用

2021-08-28 16:30:57 字數 1001 閱讀 3466

list是python中最常用的資料結構

name_list = ["zhangsan", "lisi", "wangwu"]

# 1.取值和索引

print(name_list[2])

print(name_list.index("zhangsan"))

# 2.修改

name_list[0] = "xiaoming"

# 3.增刪

# insert 方法在指定索引處插入資料

name_list.insert(1, "xiaohua")

# extend將乙個列表追加到另乙個列表後面

name_list.extend(["sunwukong", "zhubajie"])

# 4.刪除

# remove刪除指定元素的第乙個(可能有重複值)

name_list.remove("xiaohua")

# pop刪除list中的最後乙個資料

name_list.pop()

name_list.pop(1) # 刪除指定索引位置的資料

del name_list[1] # 刪除指定索引位置的資料

# clear

name_list.clear() # 刪除所有資料

# 5.檢視元素總個數和出現次數

# 檢視list中有幾個元素

list_len = len(name_list)

# 統計乙個元素在list中出現了幾次

count = name_list.count("zhangsan")

# 6.list排序

num_list = [1, 2, 3, 4, 5, 6]

num_list.sort() # 公升序排序,如果是字元,按照首字母順序

num_list.sort(reverse=true) # 降序排列

num_list.reverse() # 逆序(翻轉)

可以直接複製執行**檢視結果。

Python中list的各種操作

字串的sorted sorted 3569017hjsowmc2f4q 0 1 2 3 4 5 6 7 9 c f h j m o q s w 賦值與複製 a 1,2,3 b a 此時僅僅是b指向a所在的位置,並沒有單獨為b開闢記憶體單元,即b 1,2,3 若a的值發生改變,b的值 也會發生改變。c...

python中列表list的各種操作

lt 1,2,3,4,5 print lt 0 print lt 1 print lt 1 4 print len lt 修改 lt 0 100 新增的物件在列表是乙個元素 將可迭代物件的每個元素挨個新增 lt.extend hello world 在指定位置插入元素 lt.insert 3,goo...

selenium在python中的各種方法

例項 from selenium import webdriver import time from selenium.webdriver.chrome.options import options selenium的headless模式 chrome options options chrome ...