Python3.x列表及方法

Python3.x 列表及方法


列表中的方法有很多,本文僅舉出比較實用,每個方法一個使用案例。

    1.創建一個列表,並打印列表中的元素  

#打印所有元素
LIST = [1,2,3,4,["AA","BB"]]
print(LIST)
輸出: [1, 2, 3, 4, ['AA', 'BB']]

#打印列表中的某個元素-通過索引
LIST = [1,2,3,4,["AA","BB"]]
print(LIST[0])
print(LIST[4][0])
輸出: 1
      AA

    2.append() #列表添加元素,追加操作。

LIST = ['aa','bb']
LIST.append('cc')
print(LIST)
輸出: ['aa','bb','cc']

    3.extend() #一次性連續在末尾添加元素。

LIST = ['aa','bb']
LIST.extend('dd','ee')
print(LIST)
輸出: ['aa','bb','cc','dd','ee']

    4.insert() #像列表中的某個位置插入元素

LIST = ['AA','CC']
LIST.insert(1,'bb')
print(LIST)
輸出: ['AA','bb','CC']
#1爲索引,在該索引前插入元素

    5.remove() #刪除列表中的元素

LIST = [1,2,3,4,5]
LIST.remove(2)
print(LIST)
輸出: [1, 3, 4, 5]

    6.del() #刪除列表
 

LIST = [1,2,3,4,5]
del LIST[2]
print(LIST)
輸出: [1, 2, 4, 5]

#刪除整個列表
LIST = [1,2,3,4,5]
del LIST
print(LIST)
輸出: NameError: name 'LIST' is not defined

    7.pop() #刪除列表中一個元素並返回該值。

LIST = [1,2,3,4,5]
haha = LIST.pop(2)
print(haha)
print(LIST)
輸出: 3
      [1, 2, 4, 5]

    8.sort() #列表元素排序

LIST = [1,3,2,4,5]
LIST.sort()
print(LIST)
#倒敘
LIST.sort(reverse=True)
print(LIST)

輸出:
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

    9.count() #統計字符串裏某個字符在列表中出現的次數

LIST = "blog.csdn.net/blog"
n = LIST.count("blog")
print(n)
n = LIST.count("blog",4,len(LIST))
print(n)
輸出:
2
1

    10.list.index()  #從列表中找出某個值第一個匹配項的索引位置。

LIST = ["aa","bb","cc"]
n = LIST.index('aa')
print(n)
輸出: 0

#通過索引範圍查找
LIST = ["aa","bb","cc"]
n = LIST.index('aa', 1,2)
print(n)
輸出: 'aa' is not in list

     11.xxx in LIST or xxx not in LIST #判斷列表中元素是否存在返回boll值

number = [123, 456, 789]
n = 123 in number
print(n)
n = 123 not in number
print(n)
輸出: 
True
Flase

    12.LIST[0:3] #顯示列表中的元素

#顯示第一到第三個元素
LIST = [1,2,3,4,5]
print(LIST[0:3])
輸出: [1,2,3]

#複製一個列表爲LIST1
LIST = [1,2,3,4,5]
LIST1 = LIST[:]
print(LIST1)
輸出: [1,2,3,4,5]

#列表標籤指向LIST1
LIST = [1,2,3,4,5]
LIST = LIST1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章