iT邦幫忙

2021 iThome 鐵人賽

DAY 8
1
Software Development

宇宙 69 大魔王的 python 世界系列 第 8

【Day 08】List 介紹!

前言

list 是 Python 中最常見的資料類型,有許多的應用都會用到 list 喔!

今天會先介紹怎麼建立,還有一些基本的增加 or 刪除 list 內元素的方法。

List

建立 list

listtuple 的規則基本一樣,但是是用 [] 來把元素包含在內

x = []    #建立一個空的 list
y = ['blue', 2, 'red']
print(x)
print(y)

  • 也可以按照索引值取出

    y = ['blue', 2, 'red']
    print(y[2])
    

    y = [1, 5, 3, 4, 5, 2, 6]
    print(y[1:5])
    

  • list 內可以存重複的元素

    y = ['blue', 2, 'red', 'red']
    

list Operations

list 也可以像 str 一樣,使用 +, * 等等符號來組合 list,或著用 in 來判斷裡面有沒有特定的元素

x = [1, 2, 3]
y = ['red', 2, 'yellow']
print(x + y)
print(x * 2)
print(2 in x)    #輸出的是 True 或 False

list methods

  • list.append():將元素加到 list 的尾端,() 內放要加入的東西

    x = ['red', 2, 'yellow']
    x.append('orange')
    print(x)
    

  • list.insert():將元素加到 list 的特定位置

    'orange' 加入到 list 的第 0

    x = ['red', 2, 'yellow']
    x.append(0, 'orange')
    print(x)
    

  • list.extend():將另一個可迭代對象(tuples, sets, dictionaries 等)加入到 list 的後面

    • 把兩個 list 串起來
    x = ['red', 2, 'yellow']
    yyy = ['one', 'two', 'three']
    x.extend(yyy)
    print(x)
    

    • 也可以放 tuples, sets, dictionaries
    x = ['red', 2, 'yellow']
    yyy = ('o', 'w', 'o')
    x.extend(yyy)
    print(x)
    

    後面接 dict 範例

    x = ['red', 2, 'yellow']
    dic = {'a':'A', 'b':'B'}
    x.extend(dic)
    print(x)
    

  • list.remove():將元素從 list 中移除

    他會移除的是 () 內的元素

    x = ['red', 2, 'yellow']
    x.remove('red')
    print(x)
    

  • list.pop(index):將 list 中的第 index 個元素移除,不指定則預測為最後一個

    沒有指定的 index 的話就會把 list 內最後一個元素移除

    x = ['red', 2, 'yellow']
    x.pop()
    print(x)
    

    指定移除 x[1] 所以 2 會被移除

    x = ['red', 2, 'yellow']
    x.pop(1)
    print(x)
    

  • del:將 list 特定的 index 移除,也可以移除整個 list

    加索引值的會就跟上面 list.pop(index) 效果一樣

    x = ['red', 2, 'yellow']
    del x[2]
    print(x)
    

    如果只是打 del list 會直接把整個 list 刪除喔!

    x = ['red', 2, 'yellow']
    del x
    
  • list.clear():清空 list

    這個函式只會把 list 清空,不會像 del list 把整組都刪掉,可以根據需求選擇需要的函式

    x = ['red', 2, 'yellow']
    x.clear()
    print(x)
    

待續...


上一篇
【Day 07】tuple 介紹!
下一篇
【Day 09】if ... else
系列文
宇宙 69 大魔王的 python 世界30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言