python列表的一些常用方法以及函數


學習到了一些關於python列表的新知識,自己整理了一下,方便大家參考:

 

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# File_type:列表的常用操作方法,以及一些常用的函數
# Filename:list_function_test.py
# Author:smelond

 

方法:

1、list.count()統計:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list_count = list.count(4) # 統計某個元素在列表中出現的次數 print("4 在列表中出現過 %s 次" % list_count)

4 在列表中出現過 2 次

 

2、list.append()添加對象:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.append("obj") # 在列表末尾添加新的對象 print(list)

[6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 'obj']

 

3、list.extend()擴展列表:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list1 = [123, 456, 789] list.extend(list1) # 擴展列表,在列表末尾一次性追加另一個列表中的多個值(相當於把list1的元素復制到了list) print(list)

[6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 123, 456, 789]

 

4、list.pop()刪除對象:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.pop(1)#移出列表中的一個元素,(默認最后一個元素) print(list)

[6, 5, 2, 744, 1, 76, 13, 8, 4]

 

5、list.remove()刪除匹配項:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.remove(4) # 移除列表中某個值的第一個匹配項(只會移出第一個) print(list)

[6, 5, 2, 744, 1, 76, 13, 8, 4

 

6、list.insert()插入對象:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.insert(3, "test")#將對象插入列表的第三個位置 print(list) [6, 4, 5, 'test', 2, 744, 1, 76, 13, 8, 4]

 

7、list.copy復制列表:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list1 = list.copy()    # 復制一個副本,原值和新復制的變量互不影響
print(list1)

[4, 8, 13, 76, 1, 744, 2, 5, 4, 6]

 

8、list.reverse()反向排序:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.reverse() # 反向列表中元素 print(list) [4, 8, 13, 76, 1, 744, 2, 5, 4, 6]

 

9、list.index()獲取索引:

# 修改第一個獲取到對象
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list_index = list.index(4) # 從列表中找出某個值第一個匹配項的索引位置 list[list_index] = 999 #將我們獲取到的索引給他修改為999 print(list)

[6, 999, 5, 2, 744, 1, 76, 13, 8, 4]
# 修改所有獲取到對象
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
for
i in range(list.count(4)): # 用列表的方法count找到有多少元素等於4,然后for在來循環 list_index = list.index(4) # 找到的每一個4都用來賦給list_index list[list_index] = 999 # 最后將最后將我們獲取到的索引改為999 print(list)   # print我放入了for循環里面,所以輸出了兩條,但是從這里我們可以看到,第一次改了第一個4,第二次改了第二個4

[6, 999, 5, 2, 744, 1, 76, 13, 8, 4]
[6, 999, 5, 2, 744, 1, 76, 13, 8, 999]

 

10、list.sort()排序:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
list.sort()#對原列表進行排序.根據ascii排序 print(list)

[1, 2, 4, 4, 5, 6, 8, 13, 76, 744]

 

11、list[obj]步長:

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
print(list[0:-1:2])  # 這個被稱為步長,最后一個2代表每隔2個元素打印一次,默認就是一步
print(list[::2])  # 這種效果和上面差不多,如果是從0開始,可以把0省略不寫

 

函數:

12、len(list):

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
len(list)    # 返回列表元素的個數
print(len(list))

10

 

13、max(list):

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
print(max(list))# 返回列表元素的最大值

744

 

14、min(list):

list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4]
print(min(list))# 返回列表元素的最小值

744

 

最后更新時間:2017-11-18-19:26:35


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM