【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)
    

待续...


<<:  Day23 Lab 2 - Object storage的RAID实作2

>>:  Day8 Let's ODOO: View(1) Basic Views

消息身份验证代码(message authentication code)

-CBC-MAC(来源:https : //en.wikipedia.org/wiki/CBC-M...

Day30-"总复习"

复习前面所提到的内容 C常见的函式库有 <stdio.h> 标准输入与输出 <st...

初学者跪着学JavaScript Day7 : 资料型别 : Symbol

一日客家话:中文:茄子 客语:雕吹 当作是一种语言扩充机制 primitive data type ...

Day8-TypeScript(TS)的介面型别(Interface)Part 1

今天要来介绍TypeScript(TS)的介面型别(Interface) 首先了解TS的核心原则之一...

Day 24 [Python ML、资料视觉化] 如何选择图表型态

你学到了甚麽? 我们可以将学到的图表分为3类 Trends - 可以定义一种变换的模式 sns.li...