天天看點

Python2 清單 (list)的基本操作

1、list函數

list函數适用于所有類型的序列

根據字元串建立清單

hello = list(‘hello’),則hello的值為[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

可以使用”.join()函數将字元串清單轉換成字元串

例:

”.join([‘h’, ‘e’, ‘l’, ‘l’, ‘o’])的值為:’hello’

2、給清單元素指派

x = [1,2,3]

x[1] = 4

則修改後x的值将變為[1,4,3]

3、删除元素

從清單中删除元素可以使用:del 語句來實作,删除元素後清單的長度會随之變短

例:

del hello[2] 則hello的值将變為:[‘h’, ‘e’, ‘l’, ‘o’]

del hello[1:3]hello的值将變為:[‘h’]

4、分片指派

例:一次為多個元素指派

py = list(‘per’)

py[1:] = list(‘thon’)則py的值變為:[‘p’, ‘t’, ‘h’, ‘o’, ‘n’]

例:在不删除原有元素的情況下插入新元素

py = list(‘pn’)

py[1:1] = list(‘ytho’)則py的值變為:[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

例:通過分片指派來删除元素

py[1:5] = [] 則py的值變為:[‘p’, ‘n’]