新聞中心
在Python中,創(chuàng)建列表的方法有很多,以下是一些常用的方法:

創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供蘭坪網(wǎng)站建設(shè)、蘭坪做網(wǎng)站、蘭坪網(wǎng)站設(shè)計、蘭坪網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、蘭坪企業(yè)網(wǎng)站模板建站服務(wù),10多年蘭坪做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
1、使用方括號[]創(chuàng)建一個空列表:
my_list = []
2、使用方括號[]創(chuàng)建一個包含元素的列表:
my_list = [1, 2, 3, 4, 5]
3、使用list()函數(shù)將其他可迭代對象(如字符串、元組等)轉(zhuǎn)換為列表:
my_string = "hello" my_list = list(my_string)
4、使用*操作符將一個列表重復(fù)多次:
my_list = [1, 2, 3] repeated_list = my_list * 3
5、使用range()函數(shù)生成一個整數(shù)序列的列表:
my_list = list(range(5))
6、使用列表推導(dǎo)式創(chuàng)建一個新的列表:
my_list = [x * 2 for x in range(5)]
7、使用append()方法向列表添加元素:
my_list = [1, 2, 3] my_list.append(4)
8、使用insert()方法在指定位置插入元素:
my_list = [1, 2, 3] my_list.insert(1, 4)
9、使用extend()方法將另一個列表的元素添加到當(dāng)前列表:
my_list = [1, 2, 3] another_list = [4, 5, 6] my_list.extend(another_list)
10、使用remove()方法從列表中刪除指定元素:
my_list = [1, 2, 3, 4, 5] my_list.remove(3)
11、使用pop()方法移除并返回指定索引的元素,如果不提供索引,則默認(rèn)移除并返回最后一個元素:
my_list = [1, 2, 3, 4, 5] last_element = my_list.pop()
12、使用del關(guān)鍵字刪除指定索引的元素或切片:
my_list = [1, 2, 3, 4, 5] del my_list[1] del my_list[1:3]
13、使用clear()方法清空列表:
my_list = [1, 2, 3, 4, 5] my_list.clear()
14、使用count()方法計算列表中指定元素的出現(xiàn)次數(shù):
my_list = [1, 2, 3, 2, 1, 2, 3, 1, 1] count = my_list.count(1)
15、使用index()方法獲取指定元素的索引:
my_list = [1, 2, 3, 4, 5] index = my_list.index(3)
16、使用reverse()方法反轉(zhuǎn)列表:
my_list = [1, 2, 3, 4, 5] my_list.reverse()
17、使用sort()方法對列表進(jìn)行排序(默認(rèn)升序):
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] my_list.sort()
18、使用sorted()函數(shù)對列表進(jìn)行排序(返回一個新列表,不改變原列表):
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] sorted_list = sorted(my_list)
分享文章:python如何創(chuàng)建列表
文章來源:http://www.5511xx.com/article/cdpgjso.html


咨詢
建站咨詢
