Python入门(十):列表基本操作

    科技2022-08-10  111

    点击跳转 《Python入门系列目录》


    列表是Python对象作为其元素并按顺序排列构成有序集合

    创建列表

    方括号[]创建通过list()函数将元组、字符串或者集合转化成列表直接使用list()函数会返回一个空列表 l = list('hello world') print(l) # ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

    索引

    列表索引访问提取用下标即可,也存在正索引和负索引

    ls = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] print(ls[1:4:0]) # ValueError: slice step cannot be zero print(ls[:-7:-2]) # step是负数,默认从-1开始,[100, 80, 60] print(ls[1:8:-2]) # []

    增添

    L.append(x)

    在列表末尾添加一个元素x**(专属于列表)** # 列表中添加元素100(append) L = [0, 1, 2, 3, 4, 5] for e in L: print(e, end=' ') if e == 0: L.append(100) # 0 1 2 3 4 5 100

    L.extend(t)、+、+=

    在列表末尾添加另一个列表L = L + [i] 速度慢,因为要产生新列表 # 列表中添加元素100(+) L = [0, 1, 2, 3, 4, 5] for e in L: print(e, end=' ') if e == 0: L = L + [100] # 此时这个L是一个新的L,所以并不会打印出100 # 0 1 2 3 4 5

    L.insert(i, x)

    在列表中添加一个元素,可以指定位置添加。当插入位置超出列表尾端,则插入列表最后 # 列表中添加元素100(insert)错误 L = [0, 1, 2, 3, 4, 5] for e in L: print(e, end=' ') if e == 0: L.insert(0, 100) # 死循环,一直输出0,因为insert之后,后面的元素全部往后移 # 列表中添加元素100(insert)正确 L = [0, 1, 2, 3, 4, 5] for e in L: print(e, end=' ') if e == 0: L.insert(len(L), 100) # 0 1 2 3 4 5 100

    删除

    del L[i] 删除指定位置元素 L.pop(i) 删除指定位置元素,当不指定位置时,默认为-1 L.remove(x) 删除指定元素 # 移除列表中为0的元素(错误) L = [0, 0, 1, 2, 3, 0, 1] i = 0 while i < len(L): if L[i] == 0: L.remove(0) i += 1 print(L) # [1, 2, 3, 0, 1] # 删掉第一个0后,i变成1,跳过了第二个0 # 移除列表中为0的元素(改进1) L = [0, 0, 1, 2, 3, 0, 1] i = 0 while 0 in L: L.remove(0) print(L) # [1, 2, 3, 1] # 移除列表中为0的元素(改进2) L = [0, 0, 1, 2, 3, 0, 1] i = 0 while i < len(L): if L[i]==0: L.remove(0) else: i+=1 print(L) # [1, 2, 3, 1] # 移除列表中为0的元素(改进3),速度最快,因为L.remove(0)得每次重新遍历列表寻找0 L = [0, 0, 1, 2, 3, 0, 1] L1 =[] for e in L: if e!=0: L1.append(e) print(L1) # [1, 2, 3, 1]

    修改

    列表必须通过显式的数据赋值才能生成,将一个列表赋值给另一个列表不会生成新的列表对象

    ls = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] lt = ls ls[0] = 0 print(lt) # 同时修改了ls和lt,[0, 20, 30, 40, 50, 60, 70, 80, 90, 100]

    副本

    通过copy、切片操作、list()创建副本

    a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] b = a.copy() c = a[:] d = list(a) e = a print(id(a), id(b), id(c), id(d), id(e)) # 只有e和a是相同内存地址

    查询

    L.index(x) 查询x在列表中第一次出现的位置索引 元素 in 列表对象 判断元素是否至少在列表中出现过一次

    其他常用操作

    list.count(x)

    返回x在列表中出现的次数

    list.sort(不需要重新赋值,直接list.sort())

    sorted(需要重新赋值,ls = sorted(ls))

    list.reverse()

    len(L)

    *

    for e in L

    e:可以是多变量 for x, y in [(1, 2), (2, 3), ("hello", "world")]: print(x, y) ''' 输出 1 2 2 3 hello world '''
    Processed: 0.012, SQL: 8