Python 列表的操作

2021-09-07 16:03:36 字數 1807 閱讀 2728

list基本操作

#列表

string = '

list'#

字串->列表

list1 = list(string) #

['l', 'i', 's', 't']

#列表->字串

string1 = ''.join(list1) #

list

#列表的增刪改查

list1 = list('

this is a list

')

#增加

!') #

末尾增加元素

list1.insert(2,'

this is index 3

') #

指定index增加乙個元素

#刪除

list1.pop(-1) #

刪除指定index的元素 預設是-1 return被刪除元素的值

del list1[-1] if'

!'in list1: #

刪除第乙個匹配的元素,如果不存在會報錯,沒有返回值

list1.remove('!'

) #

修改

list1[0] = '0'

#元素賦值

list1[0:2] = list('

05') #

分片賦值

list1[1:1] = list('

1234

') #

分片賦值 插入新元素

list1[1:5] = #

分片賦值 刪除元素

#查詢 if'

a'inlist1:

index = list1.index('

a') #

查詢元素下標

#拼接

list2 = ['

new','

list

']

list1.extend(list2)

#從列表增加元素

print

list1

#逆置

list1.reverse();

print

list1

#去重

#1

l1 = ['

b','

c','

d','

c','

a','a'

] l2 =list(set(l1))

#2

l2.sort(key=l1.index) #

保持原來的順序

#3

l1 = ['

b','

c','

d','

c','

a','a'

] l2 =

for i in l1: #

ifnot i in

l2:

print l2 #

保持原來的順序

列表公升序排序和降序排序

元祖和列表的區別

python列表建立操作 python列表操作

建立列表 sample list a 1,a b python 列表操作 sample list a b 0,1,3 得到列表中的某乙個值 value start sample list 0 end value sample list 1 刪除列表的第乙個值 del sample list 0 在列...

python列表建立操作 python列表操作

列表是最常用的python資料型別,它可以作為乙個方括號內的逗號分隔值出現。列表的資料項不需要具有相同的型別。如 list a b 2,5,1 1 新建列表 stus 建立空列表 stus1 list 建立空列表 print stus print stus1 stus 范冰冰 維達 soon 上述 ...

python 列表操作

list 一種順序儲存結構,序列的一種,列表元素可以是任何型別,類似陣列,引用型別。格式定義 olist 1,str 定義乙個空的list olist 獲取列表元素個數 len olist 刪除乙個列表 del olist 刪除乙個列表元素 del list i 支援 olist1 olist2 列...