python內置數據結構學習
1. 列表List
列表list可以實現增加,刪除,查找操作
>>> list = ['dog','cat','mouse']; >>> list ['dog','cat','mouse']
>>> list.append('monkey'); >>>list ['dog','cat','mouse','monkey']
1-2. 列表元素的刪除,remove(value)
>>> list.remove('cat'); # 如果刪除的元素不存在,則會ValueError錯誤 >>> list ['dog','mouse','monkey']
>>> list.insert(1, 'donkey'); >>> list ['dog','donkey','mouse','monkey']
1-4. 刪除並返回指定元素, pop(index)
pop(): 刪除list的最後一個元素,並返回該元素
pop(index): 刪除指定下標的元素並返回該元素
>>> list ['dog', 'donkey', 'mouse', 'monkey'] >>> list.pop(); # 沒有給定下標,則刪除list的最後的元素,並返回該元素 'monkey' >>> list ['dog', 'donkey', 'mouse'] >>> list.pop(1); # 指定刪除下標為1的元素,並返回該元素 'donkey' >>>list ['dog','mouse']
1-5. 列表元素的查找 index(value)
>>> list = ['dog','cat','mouse','monkey']
>>> list.index('cat'); # 在list中查找‘cat’元素,返回list中‘cat’的下標
2
>>> list.index('cat',2); # 查找list中,從下標2開始到最後,查找cat元素
ValueError # 如果查找不到則返回錯誤
>>> list.index('cat',1,3); # 下標1-3的元素中查找cat元素
1
1-6. 列表元素的排序 sort()
*reverse默認為False,表示按照首字母升序排列,如果設置reverse=True,表示按照首字母降序排列*
>>> list = ['dog', 'cat', 'mouse', 'ant'] >>> list.sort() # 默認按照首字母生序排列 ['ant', 'cat', 'dog', 'mouse'] >>> list.sort(reverse=True); # reverse=True,按照首字母降序排列 ['mouse', 'dog', 'cat', 'ant']
1-7. 列表元素的翻轉 reverse();
>>>list = ['dog', 'cat', 'mouse', 'ant'] >>>list.reverse() >>>list ['ant', 'mouse', 'cat', 'dog']
>>> list = ['dog', 'cat', 'mouse', 'ant'] >>> list[1] # 輸出下標為1的元素 'cat' >>> list[-2] # 輸出從後往前下標為2的元素 'mouse'
1-9. 列表的子列表 list[start:end]
>>> list = ['dog', 'cat', 'mouse', 'ant'] >>> list[1:3] # 下標1-3的子列表 ['cat', 'mouse', 'ant'] >>> list[:2] # 下標0-2的子列表 ['dog', 'cat'] >>> list[2:] # 下表2-list.length的子列表 ['mouse','ant']
1-10. 列表元素的遍歷
Tags: monkey python insert False 元素
文章來源: