python資料型別之列表

2021-10-03 05:58:11 字數 1850 閱讀 6430

列表是任意物件的有序集合,那麼它的資料形態是怎樣的呢?可以進行哪些操作呢?

建立列表時,用逗號分隔不同的值,然後使用方括號括起來。

list1 =[1

,2,3

,4]list2 =

['a'

,'b'

,'c'

]list3 =

['friday',2

,3,4

]

通過下標索引來檢視列表中的值,也可以和字串一樣使用方括號擷取字元

list1[0]

list1[0:

2]

和字串不同,列表支援原位修改

list1 =[1

,2,3

,4]list1[0]

='hello'

out[1]

:['hello',2

,3,4

]

list1 =[1

,2,3

,4]'hello'

)out[2]

:[1,

2,3,

4,'hello'

]

可以使用 extend() 方法在原列表末尾新增新列表

list1 =[1

,2,3

,4]list2 =

['hello'

,'friday',5

,6]list1.extend(list2)

out[3]

:[1,

2,3,

4,'hello'

,'friday',5

,6]

可以使用 pop() 方法來移除列表中的值

list1 =[1

,2,3

,4]list1.pop(1)

#刪除下標索引為1的值,即為2

out[3]

:[1,

3,4]

可以使用 sort() 方法來對列表進行排序

list3 =

[1200

,442

,2454,31

,65]list3.sort(

)list3

out[4]

:[31,

65,442,

1200

,2454

]

可以使用 reverse() 方法來反向列表

list3 =

[1200

,442

,2454,31

,65]list3.reverse(

)list3

out[4]

:[2454

,1200

,442,65

,31]

可以使用 index() 方法從列表中找出某個值的索引位置

list2 =

['hello'

,'friday',5

,6]list2.index(

'hello'

)list2.index(

5)

可以使用 count() 方法統計某個元素在列表**現的次數

list4 =[1

,2,3

,4,'hello'

,'friday',1

,1]list4.count(1)

out[5]

:3list4.count(

'hello'

)out[6]

:1

python資料型別之列表

li print li,type li 輸出結果 li 1,2.2,true,hello print li,type li 輸出結果 1,2.2,true,hello li 1,2,3,false,python 1,2,3,4,5 print li,type li 輸出結果 1,2,3,false,...

Python資料型別之列表

print 新增後的list12 list12 extend 在末尾一次性在另乙個列表中的多個值 list13 1,2,3 list13.extend 4,5,6 list13.extend list12 print list13 insert a,b 在指定下標a新增乙個元素b,不覆蓋元素,原資料...

Python資料型別之列表

所謂的列表就像乙個容器,你可以對列表中的東西進行增刪改查,列表是可變的,但是元組是不可變的 coding utf 8 列表的增刪改查 listman name oliver age 13 male print 原始列表 print listman 增加 height 180 print 新增身高後的...