定义列表 python中用中括号[]表示列表,列表元素用逗号(,)隔开
1 2 3 4 5 6 7 >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> print(cells)['cellA' , 'cellB' , 'cellC' ] 定义一个空的列表 >>> cells = []>>> print(cells)[]
索引介绍及访问列表元素 python列表中,索引是从0开始的,而不是1,所以第一个元素索引为0。
1 2 3 4 5 6 7 8 9 10 11 >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> print(cells[0 ])cellA >>> print(cells[1 ])cellB >>> print(cells[2 ])cellC >>> print(cells[-1 ]) cellC >>> print(cells[-2 ]) cellB
修改列表元素 1 2 3 4 5 6 >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> print(cells)['cellA' , 'cellB' , 'cellC' ] >>> cells[0 ] = 'blockA' >>> print(cells)['blockA' , 'cellB' , 'cellC' ]
添加元素到列表”append” 1 2 3 4 >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> cells.append('cellD' )>>> print(cells)['cellA' , 'cellB' , 'cellC' , 'cellD' ]
列表中插入元素”insert” 1 2 3 4 >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> cells.insert(0 ,'cellX' )>>> print(cells)['cellX' , 'cellA' , 'cellB' , 'cellC' ]
删除列表中的元素”del” 1 2 3 4 5 6 7 8 >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> del cells[0 ]>>> print(cells)['cellB' , 'cellC' ] >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> del cells[-1 ]>>> print(cells)['cellA' , 'cellB' ]
弹出列表中指定元素“pop()” 1 2 3 4 5 6 >>> cells = ['cellA' ,'cellB' ,'cellC' ]>>> second_cell = cells.pop(1 )>>> print('The second cell is ' + second_cell + '.' )The second cell is cellB. >>> print(cells)['cellA' , 'cellC' ]
根据索引值删除列表中元素“remove()” 1 2 3 4 >>> cells = ['cellA' ,'cellB' ,'cellC' ,'cellA' ]>>> cells.remove('cellA' )>>> print(cells)['cellB' , 'cellC' , 'cellA' ]
永久性排序列表“sort()” 1 2 3 4 >>> cells = ['cellB' ,'cellD' ,'cellC' ,'cellA' ]>>> cells.sort()>>> print(cells)['cellA' , 'cellB' , 'cellC' , 'cellD' ]
sort(reverse=True)可以反向排序 1 2 3 4 >>> cells = ['cellB' ,'cellD' ,'cellC' ,'cellC' ]>>> cells.sort(reverse=True )>>> print(cells)['cellD' , 'cellC' , 'cellC' , 'cellB' ]
临时性排序列表”sorted()” sorted不会永久改变列表顺序,只是临时的
1 2 3 4 5 6 7 8 9 10 >>> cells = ['cellB' ,'cellD' ,'cellC' ,'cellA' ]>>> print('original list is:' );print(cells)original list is : ['cellB' , 'cellD' , 'cellC' , 'cellA' ] >>> print('sorted list is:' );print(sorted(cells))sorted list is : ['cellA' , 'cellB' , 'cellC' , 'cellD' ] >>> print('original list is:' );print(cells)original list is : ['cellB' , 'cellD' , 'cellC' , 'cellA' ]
反转列表”reverse” 1 2 3 4 5 6 >>> cells =['cellA' , 'cellB' , 'cellC' , 'cellD' ]>>> print(cells)['cellA' , 'cellB' , 'cellC' , 'cellD' ] >>> cells.reverse()>>> print(cells)['cellD' , 'cellC' , 'cellB' , 'cellA' ]
获取列表长度”len” 1 2 3 >>> cells =['cellA' , 'cellB' , 'cellC' , 'cellD' ]>>> len(cells)4
原文作者: ICtechO
原文链接: http://www.ictech.xyz/2020/python-list/
版权声明: 转载请注明出处(必须保留作者署名及链接)