【列表】
这篇文章总结了列表操作的函数大全。
>>>aList = [2,9,5,6,12,0,4,7,5]
>>>aList
>[2, 9, 5, 6, 12, 0, 4, 7, 5]
2.indexing:根据索引号取元素
>>>aList[3]
>6
3.concatenation:组合两个列表
>>>bList = [True,'Asher']
>>>aList + bList
>[2, 9, 5, 6, 12, 0, 4, 7, 5, True, 'Asher']
4.repetition:将一个列表重复N次
>>>cList = 3*bList
>>>cList
>[True, 'Asher', True, 'Asher', True, 'Asher']
PS:需要注意重复对象是如果对原序列的多次引用,改列表原列表的值,对应值也会更改
>>>dList = 3*[bList]
>>>dList
>[[True, 'Asher'], [True, 'Asher'], [True, 'Asher']]
>>>bList[1] = 2
>>>cList
>[[True, 2], [True, 2], [True, 2]]
5.length:列表长度
>>>len(aList)
>9
6.slicing:列表切片
>>>aList[2:5]
>[5, 6, 12]
>>>aList = [2,9,5,6,12,0,4,7,5]
>>>aList
>[2, 9, 5, 6, 12, 0, 4, 7, 5]
1.append and extend:列表末尾添加元素
#append:在列表的末尾添加一个对象
>>>aList.append('Asher')
>>>aList
>[2, 9, 5, 6, 12, 0, 4, 7, 5, 'Asher']
>>>aList.append([1,2,5])
>>>aList
>[2, 9, 5, 6, 12, 0, 4, 7, 5, 'Asher', [1, 2, 5]]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
#extend:合并两个列表
>>>aList.extend([1,2,5])
>>>aList
>[2, 9, 5, 6, 12, 0, 4, 7, 5, 1, 2, 5]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
2.insert:插入元素到列表中
#insert(i,item):在列表的第i个位置插入元素item
>>>aList.insert(2,[1,2,5])
>>>aList
>[2, 9, [1, 2, 5], 5, 6, 12, 0, 4, 7, 5]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
3.pop and del and remove:删除列表中元素
#pop默认删除列表的最后一个元素
>>>aList.pop()
>>>aList
>[2, 9, 5, 6, 12, 0, 4, 7]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
#pop(i):删除列表的第i个元素
>>>aList.pop(2)
>>>aList
>[2, 9, 6, 12, 0, 4, 7, 5]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
#del List[i]:删除列表的第i个元素
>>>del aList[2]
>>>aList
>[2, 9, 6, 12, 0, 4, 7, 5]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
#remove(item):删除列表中首次出现的item元素
>>>aList.remove(5)
>>>aList
>[2, 9, 6, 12, 0, 4, 7, 5]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
4.sort:列表排序
#sort:对列表进行排序
>>>aList.sort()
>>>aLis
>[0, 2, 4, 5, 5, 6, 7, 9, 12]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
5.reverse:列表反转
>>>aList.reverse()
>>>aList
>[5, 7, 4, 0, 12, 6, 5, 9, 2]
#还原列表aList
>>>aList = [2,9,5,6,12,0,4,7,5]
6.index:返回列表中首次出现某元素索引
>>>aList = [2,9,5,6,12,0,4,7,5]
>>>aList.index(5)
>2
7.count:列表元素计数
>>>aList.count(5)
>2