Python學習-基礎語法篇
阿新 • • 發佈:2022-05-24
列表
# 定義一個列表 aa
>>> aa = [1, 2, 3, 4, 5, 'hhh']
# 列印一個列表
>>> print(aa)
[1, 2, 3, 4, 5, 'hhh']
# 下標獲取值
>>> length = len(aa)
>>> aa[length - 1]
'hhh'
>>> aa[-1]
'hhh'
>>> aa[-2]
5
# 擷取值
>>> aa[0:3]
[1, 2, 3]
>>> aa[3-4]
'hhh'
>>> aa[3:4]
[4]
>>> aa[3:6]
[4, 5, 'hhh']
>>> aa[3:]
[4, 5, 'hhh']
>>> aa[:3]
[1, 2, 3]
>>> aa[0:3:2]
[1, 3]
>>> aa[::2]
[1, 3, 5]
>>> aa[::-2]
['hhh', 4, 2]
>>> aa[::-1]
['hhh', 5, 4, 3, 2, 1]
列表 增刪改查
# 新增元素 在末尾新增
>>> aa.append("ppp") #新增一個元素
>>> aa
[1, 2, 3, 4, 5, 'hhh', 'ppp']
>>> aa.extend(["6","7",]) # 新增多個元素
>>> aa
[1, 2, 3, 4, 5, 'hhh', 'ppp', '6', '7']
# len(s) 表示列表末尾
>>> s = ["one", "two"]
>>> s
['one', 'two']
>>> s[len(s):] = [1,2,3]
>>> s
['one', 'two', 1, 2, 3]
# 插入元素 insert 指定下標 元素值
>>> s = [1,3,4,5]
>>> s
[1, 3, 4, 5]
>>> s.insert(1, 2)
>>> s
[1, 2, 3, 4, 5]
>>> s.insert(0, 0)
>>> s
[0, 1, 2, 3, 4, 5]
>>> s.insert(len(s), 6)
>>> s
[0, 1, 2, 3, 4, 5, 6]
>>> len(s) # 表示列表末尾的下標值
7
>>> s
[0, 1, 2, 3, 4, 5, 6]
>>> aa
[1, 2, 3, 4, 5, 'hhh', 'ppp', '6', '7']
# 刪除指定元素的值,存在多個元素,刪除最小下標的值
>>> aa.remove("ppp")
>>> aa
[1, 2, 3, 4, 5, 'hhh', '6', '7']
# pop刪除下標的值
>>> aa.pop(5)
'hhh'
>>> aa
[1, 2, 3, 4, 5, '6', '7']
# 清空列表
>>> aa.clear()
>>> aa
[]
# 改/替換 列表是可變的 字串是不可變的
>>> aa = [1, 2, 3, 4, 5, 'hhh']
>>> aa[5] = "ppp"
>>> aa
[1, 2, 3, 4, 5, 'ppp']
# 替換連續的元素 把下標3以後的元素全部替換
>>>