新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python怎樣清空數(shù)組元素
通常情況下,python中的數(shù)組指的是列表,清空列表可以使用clear()方法。下面是列表的一些其他操作方法

成都創(chuàng)新互聯(lián)公司是一家朝氣蓬勃的網(wǎng)站建設公司。公司專注于為企業(yè)提供信息化建設解決方案。從事網(wǎng)站開發(fā),網(wǎng)站制作,網(wǎng)站設計,網(wǎng)站模板,微信公眾號開發(fā),軟件開發(fā),微信小程序,10多年建站對成都柔性防護網(wǎng)等多個方面,擁有豐富的網(wǎng)站設計經(jīng)驗。
1.創(chuàng)建列表。只要把逗號分隔的不同的數(shù)據(jù)項使用方括號括起來即可
1 list = ['wade','james','bosh','haslem']
與字符串的索引一樣,列表索引從0開始。列表可以進行截取、組合等
2.添加新的元素
1 List.append('allen') #方式一:向list結尾添加 參數(shù)object
2 >>> a=[1,2,3,4]
3 >>> a.append(5)
4 >>> print(a)
5 [1, 2, 3, 4, 5]
6
7 List.insert(4,'lewis') #方式二:插入一個元素 參數(shù)一:index位置 參數(shù)二:object
8 >>> a=[1,2,4]
9 >>> a.insert(2,3)
10 >>> print(a)
11 [1, 2, 3, 4]
12
13 List.extend(tableList) #方式三:擴展列表,參數(shù):iterable參數(shù)
14 >>> a=[1,2,3]
15 >>> b=[4,5,6]
16 >>> a.extend(b)
17 >>> print(a)
18 [1, 2, 3, 4, 5, 6]
推薦學習《python教程》
3.遍歷列表
1 for i in List: 2 print i,
4.訪問列表中的值
使用下標索引來訪問列表中的值,同樣你也可以使用方括號的形式截取字符,如下所示:
1 >>> List = [1, 2, 3, 4, 5, 6, 7 ] 2 >>> print(List[3]) 3 4
5.從list刪除元素
1 List.remove() #刪除方式一:參數(shù)object 如有重復元素,只會刪除最靠前的 2 >>> a=[1,2,3] 3 >>> a.remove(2) 4 >>> print(a) 5 [1, 3] 6 7 List.pop() #刪除方式二:pop 可選參數(shù)index刪除指定位置的元素 默認為最后一個元素 8 >>> a=[1, 2, 3, 4, 5, 6] 9 >>> a.pop() 10 6 11 >>> print(a) 12 [1, 2, 3, 4, 5] 13 14 15 del List #刪除方式三:可以刪除整個列表或指定元素或者列表切片,list刪除后無法訪問。 16 >>> a=[1, 2, 3, 4, 5, 6] 17 >>> del a[5] 18 >>> print(a) 19 [1, 2, 3, 4, 5] 20 >>> del a 21 >>> print(a) 22 Traceback (most recent call last): 23 File "", line 1, in 24 print(a)
6.排序和反轉(zhuǎn)代碼
1 List.reverse() 2 >>> a=[1, 2, 3, 4, 5, 6] 3 >>> a.reverse() 4 >>> print(a) 5 [6, 5, 4, 3, 2, 1] 6 7 8 List.sort() #sort有三個默認參數(shù) cmp=None,key=None,reverse=False 因此可以制定排序參數(shù) 9 >>> a=[2,4,6,7,3,1,5] 10 >>> a.sort() 11 >>> print(a) 12 [1, 2, 3, 4, 5, 6, 7] 13 #python3X中,不能將數(shù)字和字符一起排序,會出現(xiàn)此報錯 14 >>> a=[2,4,6,7,3,1,5,'a'] 15 >>> a.sort() 16 Traceback (most recent call last): 17 File "", line 1, in 18 a.sort() 19 TypeError: unorderable types: str() < int()
7.Python列表截取
1 Python的列表截取與字符串操作類型相同,如下所示: 2 L = ['spam', 'Spam', 'SPAM!'] 3 操作: 4 Python 表達式 結果 描述 5 L[2] 'SPAM!' 讀取列表中第三個元素 6 L[-2] 'Spam' 讀取列表中倒數(shù)第二個元素 7 L[1:] ['Spam', 'SPAM!'] 從第二個元素開始截取列表
文章名稱:創(chuàng)新互聯(lián)Python教程:python怎樣清空數(shù)組元素
新聞來源:http://fisionsoft.com.cn/article/dhhpeos.html


咨詢
建站咨詢
