Python3之列表(List)淺談

日期:2019年11月23日
作者:Commas
註釋:學習就是爲了忘記,讓我們來總結一下Python3列表的定義、11個列表方法的使用、5種列表遍歷的方法…
如果您想了解更多有關Python的知識,那麼請點《我的Python淺談系列目錄》



一、列表的定義

列表有序的可變的元素集合,每個元素都會分配一個數字,這個數字就是對應元素在列表的索引,即“列表[索引] = 元素”。

num_list = [111, 222, 333] # 列表直接定義
num_list[0] # 值爲111
num_list[1] # 值爲222
num_list[2] # 值爲333

在這裏插入圖片描述

二、列表的方法

獲取“列表方法”的方法如下:
Python語句:print(dir([]))
控制檯輸出:
[‘add’, ‘class’, ‘contains’, ‘delattr’, ‘delitem’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘getitem’, ‘gt’, ‘hash’, ‘iadd’, ‘imul’, ‘init’, ‘init_subclass’, ‘iter’, ‘le’, ‘len’, ‘lt’, ‘mul’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘reversed’, ‘rmul’, ‘setattr’, ‘setitem’, ‘sizeof’, ‘str’, ‘subclasshook’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

  1. append(object)
    Append object to the end of the list.
    在列表末尾添加新的對象
name_list = []
name_list.append("Commas")
print(name_list)
# 控制檯輸出:['Commas']
  1. insert(index, object)
    Insert object before index.
    將對象插入在列表(索引爲index元素之前的位置)
name_list = ["Commas"]
name_list.insert(0, "星爺")
print(name_list)
# 控制檯輸出:['星爺', 'Commas']
  1. extend(iterable)
    Extend list by appending elements from the iterable.
    在列表末尾一次性追加另一個序列中的多個值
    (用新列表擴展原來的列表)
name_list = ["星爺"]
temp_list = ["Commas"]
name_list.extend(temp_list)
print(name_list)
name_list.extend("123")
print(name_list)
# 控制檯輸出:
# ['星爺', 'Commas']
# ['星爺', 'Commas', '1', '2', '3']
  1. copy()
    Return a shallow copy of the list.
    返回列表的淺複製(開闢了新的內存空間)
# (1)列表方法淺複製
name_list = ["Commas"]
copy_list = name_list.copy()
copy_list.append("星爺")
print(name_list, id(name_list))
print(copy_list, id(copy_list))
# 控制檯輸出:
# ['Commas'] 1886939296008
# ['Commas', '星爺'] 1886938538568
#-------------------------
# (2)直接用賦值符號
name_list = ["Commas"]
equal_list = name_list
equal_list.append("星爺")
print(name_list, id(name_list))
print(equal_list, id(equal_list))
# 控制檯輸出:
# ['Commas', '星爺'] 1886938579720
# ['Commas', '星爺'] 1886938579720

(i)知識加油站
id(object)–> 獲得 obj 的內存地址(10進制)
(ii)小結:
1、列表的copy方法是重新開闢了一個新的內存空間,將name_list的“值”複製過去,所以在對copy_list添加元素的時候,name_list的值不變,感覺好像只是淺淺的複製了原列表的“值”,與原來列表沒有任何關聯了,所以就將該方法稱之爲列表的【淺複製】
2、賦值號操作(=)沒有開闢新的內存空間,只是複製了列表的內存地址,因爲是同一塊內存空間,在同一塊內存上修改(追加一個元素)所以name_list的值也會進行更改,稱之爲列表的【深複製】

  1. remove(object)
    Remove first occurrence of value.
    Raises ValueError if the value is not present.
    移除列表中某個值的第一個匹配項,
    若值不存在,則拋出異常。
name_list = ["逗號先生", "星爺", "達叔", "逗號先生"]
print(name_list)
name_list.remove("逗號先生")
print(name_list)
name_list.remove("Commas") #異常:ValueError
print(name_list)
# 控制檯輸出:
# ['逗號先生', '星爺', '達叔', '逗號先生']
# ['星爺', '達叔', '逗號先生']
# File "D:test.py", line 5, in <module> name_list.remove("Commas")
# ValueError: list.remove(x): x not in list

小結:
1、移除的元素是列表中第一次出現的元素;
2、如果移除的元素不在列表中,那麼會報錯。

  1. pop(index)
    Remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.
    移除列表中的一個元素(默認最後一個元素),並且返回該元素的值,
    若值不存在,則拋出異常。
name_list = ["星爺", "達叔", "Commas"]
print(name_list)
name_list.pop()
print(name_list)
name_list.pop(1)
print(name_list)
name_list.pop(6) #異常:IndexError
print(name_list)
# 控制檯輸出:
# ['星爺', '達叔', 'Commas']
# ['星爺', '達叔']
# ['星爺']
# File "D:test.py", line 5, in <module> name_list.pop(6)
# IndexError: pop index out of range

小結:
1、默認移除並返回最後一個元素,
如果index有指定,那麼久移除並返回指定元素;
2、如果pop的index超出列表的範圍,那麼會報錯。

  1. clear()
    Remove all items from list
    移除列表所有的元素(清空列表元素,列表還在)
name_list = ["星爺", "達叔", "Commas"]
print(name_list)
name_list.clear()
print(name_list)
# 控制檯輸出:
# ['星爺', '達叔', 'Commas']
# []
  1. index(object)
    Return first index of value.
    Raises ValueError if the value is not present.
    從列表中找出某個值第一個匹配項的索引位置
    若值不存在,則拋出異常。
name_list = ["星爺", "達叔", "Commas"]
index = name_list.index("達叔")
print(index)
# 指定列表下標從0到2中查詢“達叔”的下標值
index = name_list.index("達叔", 0, 2)
print(index)
index = name_list.index("逗號先生") #異常:ValueError
print(index)
# 控制檯輸出:
# 1
# 1
# File "D:test.py", line 7, in <module> 
# index = name_list.index("逗號先生")
# ValueError: '逗號先生' is not in list
  1. count(object)
    Return number of occurrences of value.
    統計某個元素在列表中出現的次數
name_list = ["星爺", "達叔", "星爺"]
count = name_list.count("星爺")
print(count)
count = name_list.count("逗號先生")
print(count)
# 控制檯輸出:
# 2
# 0
  1. reverse()
    Reverse IN PLACE.
    逆序,反轉,將列表元素的順序反過來
name_list = ["星爺", "達叔", "Commas"]
print(name_list)
name_list.reverse()
print(name_list)
# 控制檯輸出:
# ['星爺', '達叔', 'Commas']
# ['Commas', '達叔', '星爺']
  1. sort()
    Stable sort IN PLACE.
    排序,對原列表進行排序
num_list = [1, 6, 2, 9]
print(num_list)
# 升序
num_list.sort()
print(num_list)
# 降序
num_list.sort(reverse=True)
print(num_list)
# 控制檯輸出:
# [1, 6, 2, 9]
# [1, 2, 6, 9]
# [9, 6, 2, 1]

三、列表的遍歷

  1. 使用for循環遍歷
name_list = ["星爺", "達叔", "Commas"]
for name in name_list:
    print(name)

控制檯輸出結果:
星爺
達叔
Commas

  1. 使用while循環遍歷
name_list = ["星爺", "達叔", "Commas"]
# 初始化計數器
count = 0
while count < len(name_list):
    print(name_list[count])
    # 相當於count = count + 1
    count += 1

控制檯輸出結果:
星爺
達叔
Commas

  1. 使用range()遍歷
name_list = ["星爺", "達叔", "Commas"]
# (1)range(stop)
for index in range(len(name_list)):
    print(name_list[index], end=",")
print() # 換行
# (2)range(start, stop)
for index in range(1, len(name_list)):
    print(name_list[index], end=",")
print() # 換行
# (3)range(start, stop ,step)
for index in range(0, len(name_list), 2):
    print(name_list[index], end=",")

控制檯輸出結果:
星爺,達叔,Commas,
達叔,Commas,
星爺,Commas,

  1. 使用iter()遍歷
name_list = ["星爺", "達叔", "Commas"]
for value in iter(name_list):
    print(value)

控制檯輸出結果:
星爺
達叔
Commas

  1. 使用enumerate()遍歷
name_list = ["星爺", "達叔", "Commas"]
for index, value in enumerate(name_list):
    print(index, value)

控制檯輸出結果:
0 星爺
1 達叔
2 Commas

本文參考:
1、https://www.runoob.com/python/python-lists.html


版權聲明:本文爲博主原創文章,如需轉載,請給出:
原文鏈接:https://blog.csdn.net/qq_35844043/article/details/103116752

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