List 列表#
索引和切片#
列表支持索引和切片,还支持嵌套 混合
>>> [1,"2",3.5,['a','b']]
[1, '2', 3.5, ['a', 'b']]
>>> a=[1,"2",3.5,['a','b']]
>>> a[3]
['a', 'b']
>>> a[3][1]
'b'
混合,相加#
>>> my_list=[1,2,3]
>>> my_list=['STRING',100,23.2]
>>> len(my_list)
3
>>> my_list[1:]
[100, 23.2]
>>> my_list[:1]
['STRING']
>>> mylist=['one','two','three']
>>> another_list=['four','five']
>>> mylist+another_list
['one', 'two', 'three', 'four', 'five']
>>> mylist
['one', 'two', 'three']
>>> another_list
['four', 'five']
>>> new_list=mylist+another_list
>>> new_list
['one', 'two', 'three', 'four', 'five']
可修改#
>>> new_list[0]='One All Caps'
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five']
>>> new_list.append('six') #向后添加元素
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five', 'six']
>>> new_list[-1]='heihei' #修改最后一个元素
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five', 'heihei']
>>> len(new_list)
6
>>> new_list[6]='heihei' #向后添加元素不能用下标方式
Traceback (most recent call last):
File "<python-input-23>", line 1, in <module>
new_list[6]='heihei'
~~~~~~~~^^^
IndexError: list assignment index out of range
>>> new_list.pop
<built-in method pop of list object at 0x7f7a558dfb80>
#移除元素
>>> new_list.pop() #弹出并返回最后一个元素
'heihei'
>>> new_list
['One All Caps', 'two', 'three', 'four', 'five']
>>> popped_item=new_list.pop()
>>> popped_item
'five'
>>> new_list
['One All Caps', 'two', 'three', 'four']
#弹出指定索引的元素
>>> new_list
['One All Caps', 'two', 'three', 'four']
>>> new_list.pop(0)
'One All Caps'
>>> new_list
['two', 'three', 'four']
#弹出列表最后一个元素
>>> new_list.pop(-1)
'four'
>>> new_list
['two', 'three']
sort 和 reverse:(原地操作)#
sort 不返回任何类型