python之列表操作

2021-08-04 04:31:20 字數 2620 閱讀 7929

#列表操作功能彙總

print("列表操作功能彙總")

list_demo = ['first'

, 'second'

, 'thrid'

, 'fourth']

#複製list_demo列表取名list

list = list_demo[:]

print("原列表為:"

, list)

print("-----------------------------")

print("輸出列表第乙個元素:"

, list[0])

print("輸出列表最後乙個元素:"

, list[-1])

print("從2個開始到第3個輸出列表的元素:"

, list[1:3])

print("從2個開始到末尾輸出列表的元素:"

, list[1:])

print("-----------------------------")

#列表中插入元素至末尾

list = list_demo[:]

print("列表中插入元素至末尾:"

, list)

#列表中指定位置插入元素

list = list_demo[:]

list.insert(1

, "hello")

print("列表中指定位置插入元素:"

, list)

print("-----------------------------")

#刪除列表中指定位置的元素

list = list_demo[:]

dellist[1]

print("刪除列表中指定位置的元素:"

, list)

#刪除列表中指定位置的元素並記錄

list = list_demo[:]

popone = list.pop(1)

print("刪除列表中指定位置的元素並記錄:"

, list,

"; 刪掉的元素是:"

, popone)

#刪除列表中指定值的元素

list = list_demo[:]

list.remove("first")

print("刪除列表中指定值的資料:"

, list)

print("-----------------------------")

#列表解析:將for迴圈和表示式的**合併成一行

list = [value**2

forvalueinrange(1

, 5)]

print("列表解析結果:"

, list)

print("-----------------------------")

#檢查列表中是否有指定的元素:in或not in。

list = list_demo[:]

if"first"

inlist:

print("判斷'first'在列表中")

print("-----------------------------")

#判斷列表中是否有值

iflist:

print("判斷列表中有值。")

else:

print("判斷列表為空。")

執行結果:

列表操作功能彙總

原列表為: ['first', 'second', 'thrid', 'fourth']

-----------------------------

輸出列表第乙個元素: first

輸出列表最後乙個元素: fourth

從2個開始到第3個輸出列表的元素: ['second', 'thrid']

從2個開始到末尾輸出列表的元素: ['second', 'thrid', 'fourth']

-----------------------------

列表中插入元素至末尾: ['first', 'second', 'thrid', 'fourth', 'hello']

列表中指定位置插入元素: ['first', 'hello', 'second', 'thrid', 'fourth']

-----------------------------

刪除列表中指定位置的元素: ['first', 'thrid', 'fourth']

刪除列表中指定位置的元素並記錄: ['first', 'thrid', 'fourth'] ; 刪掉的元素是: second

刪除列表中指定值的資料: ['second', 'thrid', 'fourth']

-----------------------------

列表解析結果: [1, 4, 9, 16]

-----------------------------

判斷'first'在列表中

-----------------------------

判斷列表中有值。

python之列表操作

詳情見語雀 列表 增 extend 列表末尾追加乙個序列 insert 列表插入元素 copy 複製列表 列表 刪 pop 移除列表的乙個元素 預設最後乙個 並返回 remove 移除列表中某值的匹配項 clear 清除列表 列表 查 reverse 反向列表 sort 對原列表排序 list in...

python筆記之列表操作

ls1 print ls1,type ls1 列表中可以出現重複資料 ls2 1,3,2,2,3,1 print ls2 1,3,2,2,3,1 列表中可以出現不同型別的資料 ls3 1,3.14,true,空元組,但只包含乙個元素的元組表示方式 元素,空字典 print ls3 列表通過索引取值 ...

python基礎筆記之列表操作

列表簡介 列表操作 切片 data slice data 0 2 深拷貝 data list data data deep copy data data shallow copy data data 2 9print data deep copy data deep copy,data shallo...