溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python之 列表常用方法

發布時間:2020-08-09 20:13:02 來源:ITPUB博客 閱讀:201 作者:張沖andy 欄目:關系型數據庫

更多列表的使用方法和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]
print x
# 輸出:1
print y

 

remove:移除列表中某個值的第一個匹配項


# remove函數
x = ['to','be','not','to','be']
x.remove('to')
# 輸出:['be', 'not', 'to', 'be']
print x
# 移除列表沒有的元素會拋出異常
x.remove('too')

 

reverse:將列表中的元素反向存放

# reverse函數
x = [1,2,3]
x.reverse()
# 輸出:[3, 2, 1]
print x

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 x
# 輸出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
print y
# 輸出:[3, 1, 2, 7, 6, 9, 5, 4, 8]
print z

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女