Beginning Python From Novice to Professional (3) - 列表操作,pythonnovice
列表操作
list函數:
>>> list('hello')['h', 'e', 'l', 'l', 'o']改變列表:
>>> x=[1,1,1]>>> x[1]=2>>> x[1, 2, 1]
刪除元素:
>>> names = ['wu','li','zhao','qian']>>> del names[1]>>> names['wu', 'zhao', 'qian']
分區賦值:
>>> name = list('perl')>>> name['p', 'e', 'r', 'l']>>> name[2:] = list('ar')>>> name['p', 'e', 'a', 'r']
>>> num = [1,2,3,4,5]>>> num[1:4]=[] #從1位開始但不包括4位>>> num[1, 5]
append 列表末尾添加新元素:
>>> lst = [1,2,3]>>> lst.append(4)>>> lst[1, 2, 3, 4]
count 統計元素的個數:
>>> ['we','have','we','a','dog'].count('we')2extend 擴充列表:
>>> a = [1,2,3]>>> b = [4,5,6]>>> a.extend(b)>>> a[1, 2, 3, 4, 5, 6]
index 找出第一個匹配項的位置:
>>> sentence = ['I','have','a','little','dog']>>> sentence.index('little')3insert 將對象插入列表:
>>> num = [1,2,3,5,6,7]>>> num.insert(3,'four')>>> num[1, 2, 3, 'four', 5, 6, 7]
pop 移除列表元素,預設最後一個:
>>> x = [1,2,3]>>> x.pop()3>>> x[1, 2]>>> x.pop(0)1>>> x[2]
結合append:
>>> x = [1,2,3]>>> x.append(x.pop())>>> x[1, 2, 3]
remove 移除列表中的第一個匹配項:
>>> x = ['to','be','or','not','to','be']>>> x.remove('be')>>> x['to', 'or', 'not', 'to', 'be']reverse 反向存放元素:
>>> x = [1,2,3]>>> x.reverse()>>> x[3, 2, 1]
sort 排序:
>>> x = [4,6,2,1,7,9]>>> x.sort()>>> x[1, 2, 4, 6, 7, 9]
>>> x.sort(reverse=True)>>> x[9, 7, 6, 4, 2, 1]>>> x.sort(reverse=False)>>> x[1, 2, 4, 6, 7, 9]