更多清單的使用方法和API,請參考Python文檔:http://docs.python.org/2/library/functions.html
append:用于在清單末尾追加新對象:
# append函數
lst = [1,2,3]
lst.append(4)
# 輸出:[1, 2, 3, 4]
print lst
複制代碼
count:用于統計某個元素在清單中出現的次數:
# count函數
temp_str = ['to','be','not','to','be']
# 輸出:2
print temp_str.count('to')
extend:可以在清單末尾一次性追加另一個序列中的多個值,和連接配接操作不同,extend方法是修改了被擴充的序列(調用extend方法的序列),而原始的連接配接操作傳回的是一個全新的清單
# extend函數
a = [1,2,3]
b = [4,5,6]
a.extend(b)
#輸出:[1, 2, 3, 4, 5, 6]
print a
# 輸出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
print a + [7,8,9]
# 輸出:[1, 2, 3, 4, 5, 6]
print a
index:用于從清單中找出某個值第一個比對項的索引位置
# index函數
knights = ['we','are','the','knights','who','say','ni']
# 輸出:4
print knights.index('who')
# 抛出異常:ValueError: 'me' is not in list
print knights.index('me')
insert:用于将對象插入到清單中
# insert函數
numbers = [1,2,3,5,6]
numbers.insert(3,'four')
# 輸出:[1, 2, 3, 'four', 5, 6]
print numbers
pop:移除清單中的一個元素(預設是最後一個),并且傳回該元素的值。通過pop方法可以實作一種常見的資料結構——棧(LIFO,後進先出)。
# pop函數
x = [1,2,3]
x.pop()
# 輸出:[1, 2]
print x
y = x.pop(0)
# 輸出:[2]
# 輸出:1
print y
remove:移除清單中某個值的第一個比對項
# remove函數
x = ['to','be','not','to','be']
x.remove('to')
# 輸出:['be', 'not', 'to', 'be']
# 移除清單沒有的元素會抛出異常
x.remove('too')
reverse:将清單中的元素反向存放
# reverse函數
x.reverse()
# 輸出:[3, 2, 1]
sort:對清單進行排序。注意:sort函數時沒有傳回值的(None),它作用于源序列。可以通過sorted函數來擷取已排序的清單副本。
# sort函數
x = [3,1,2,7,6,9,5,4,8]
y = x[:]
z = x
y.sort()
# 輸出:[3, 1, 2, 7, 6, 9, 5, 4, 8]
print z
文章可以轉載,必須以連結形式标明出處。
本文轉自 張沖andy 部落格園部落格,原文連結: http://www.cnblogs.com/andy6/p/7965821.html,如需轉載請自行聯系原作者