Python中的列表、元组和切片:使用及区别解析

246 阅读7分钟

列表

认识

由一系列有序的元素组成,方括号 [] 表示,逗号分隔元素

colors = ["red","green","blue","yellow"]

print(colors) 打印出来的为列表的内部表示,如下:

['red', 'green', 'blue', 'yellow']

使用

1 访问列表元素

访问列表需要知道元素的位置,即索引。如访问 colors 中的第二个元素 green :

print(colors[1]) #打印结果为: green

python为访问最后一个列表元素提供了特殊语法,即 索引为-1。当我们不知道列表长度时可以通过负数索引来访问倒数第i个元素

print(colors[-1]) #打印结果为倒数第1个: yellow
print(colors[-2]) #打印结果为倒数第2个: blue

使用列表中的各个值:

print("My favorite color is " + colors[3])  #打印结果为: My favorite color is yellow

2 修改、添加、删除元素

列表是动态可变的

  • 修改元素

    将 colors 列表第3个元素修改为 purple

    colors[2] = "purple"
    print(colors)   #打印结果为: ['red', 'green', 'purple', 'yellow']3个元素的值改变了
    
  • 添加元素

    最简单的方式是将元素加到列表末尾,而不影响列表中的其他所有元素

    colors.append("white")
    print(colors[-1])   #打印结果为:white,white被追加到列表最后
    

    使用 append() 动态创建列表很方便,有些时候需要等程序运行后才知道会存储哪些数据,就可以使用 append() 在空列表中进行追加

    fruits = []
    fruits.append("apple")
    fruits.append("peach")
    print(fruits)   #打印结果为:['apple', 'peach']
    

    在列表中添加元素则需要指定要添加的位置和值,如在 fruits 列表开头添加"pear",而其他元素均右移一个位置:

    fruits.insert(0,"pear")
    print(fruits)   #打印结果:['pear', 'apple', 'peach']
    
  • 删除元素

    • del

      当知道要删除元素的索引时:

      del fruits[2]
      print(fruits)   #删除fruits列表第3个元素后,结果为:['pear', 'apple']
      

      del可删除任何位置的列表元素

    • pop()

      默认删除列表末尾的元素。这里用删除一词不太准确,应该说弹出列表元素。列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

      使用pop()删除时可接着使用它的值,如下从 colors 列表中弹出最后一个元素后,并将其存储到colors_pop中:

      colors = ["red","green","blue","yellow","white"]
      colors_pop = colors.pop()
      print(colors)   #打印结果:['red', 'green', 'blue', 'yellow']
      print(colors_pop)   #打印结果:white
      

      当知道要删除的元素的索引时,可以使用pop()来删除列表中任何位置的元素:

      colors = ["red","green","blue","yellow","white"]
      colors_pop1 = colors.pop(0)
      print(colors)   #打印结果:['green', 'blue', 'yellow', 'white']
      print(colors_pop1)  #打印结果:red
      
    • remove()

      当不知道元素的索引时,可以根据元素的值找到元素并删除

      colors = ["red","green","blue","yellow","white"]
      colors.remove("white")
      print(colors)   #打印结果:['red', 'green', 'blue', 'yellow']
      

      使用remove()从列表中删除元素时,可接着使用它的值。如下将值 “white” 存储在remove_color中,并删除列表中值与remove_color的值相同的元素:

      colors = ["red","green","blue","yellow","white"]
      remove_color = "white"
      colors.remove(remove_color)
      print(colors)   #打印结果:['red', 'green', 'blue', 'yellow']
      print("被删除的颜色是:"+ remove_white) #打印结果:被删除的颜色是:white
      

3 组织列表

  • sort()

    sort() 可以对列表永久性排序,按字母顺序排列

    colors = ["red","green","blue","yellow","white"]
    colors.sort()
    print(colors)   #打印结果:['blue', 'green', 'red', 'white', 'yellow']
    

    参数reverse=True则倒序排列:

    colors = ["red","green","blue","yellow","white"]
    colors.sort(reverse=True)
    print(colors)   #打印结果:['yellow', 'white', 'red', 'green', 'blue']
    
  • sorted()

    临时排序。当要保留列表元素原来的顺序时可以通过sorted方法实现元素按特定顺序展示。

    同理,也可向函数sorted()传递参数reverse=True

    colors = ["red","green","blue","yellow","white"]
    print(sorted(colors))   #打印结果:['blue', 'green', 'red', 'white', 'yellow']
    print(colors)   #打印结果:['red', 'green', 'blue', 'yellow', 'white']
    
  • reverse()

    反转列表元素顺序(元素位置):

    colors = ["red","green","blue","yellow","white"]
    colors.reverse()
    print(colors)   #打印结果:['white', 'yellow', 'blue', 'green', 'red']
    
  • len()

    colors = ["red","green","blue","yellow","white"]
    print(len(colors))  #打印结果:5
    

4 操作列表

  • for循环遍历列表

    for循环(从colors列表中取出第一个元素存储在变量color中,并打印color的值,如此重复执行A、B步骤)

    colors = ["red","green","blue","yellow","white"]	
    for color in colors:	#A
        print(color)	#B
    #打印结果为:
    red
    green
    blue
    yellow
    white
    
  • range()

    使用 range() 创建数值列表

    for value in range(1,5):
        print(value)
    

    此处打印为差一行为的结果:1,2,3,4.

    (函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止)

    numbers = list(range(1,6))
    print(numbers)	#打印结果: [1, 2, 3, 4, 5]
    

    指定步长:

    numbers = list(range(1,10,2))	#步长为21~9之间的数
    print(numbers)	#打印结果:[1, 3, 5, 7, 9]
    
  • 列表解析

    假如需要输出1~10中每个数的平方,可以这么做:

    squares =[]
    for value in range(1,11):
        squares.append(value**2)
    print(squares)	#打印结果:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    

    而如果使用列表解析:

    squares = [value**2 for value in range(1,11)]
    

    先指定一个描述性的列表名 squares,再指定一个左方括号,并定义一个表达式 value**2来计算平方值,然后for循环用户给表达式提供值,最后补上右方括号

  • 切片

    切片:列表的一部分

    与range一样,Python在到达你指定的第二个索引前面的元素后停止。如下,指定索引0~3的前3个元素

    colors = ["red","green","blue","yellow","white"]
    print(colors[0:3])	#索引012['red', 'green', 'blue']
    print(colors[2:4])	#索引23['blue', 'yellow']
    print(colors[:4])	#从头开始到索引3['red', 'green', 'blue', 'yellow']
    print(colors[2:])	#索引2开始到末尾所有元素:['blue', 'yellow', 'white']
    print(colors[-2:])	#从倒数第2个开始到末尾的元素:['yellow', 'white']
    

    遍历切片:

    for color in colors[:4]:	#遍历从头开始到索引3的元素
        print(color)
    
  • 复制列表

    要复制列表,可以创建一个包含整个列表的切片,同时省略起始索引、终止索引,即[:]

    new_colors = colors[:]
    print(new_colors)	#['red', 'green', 'blue', 'yellow', 'white']
    

    现在是有2个列表,下面讲讲不使用切片复制列表有什么区别:

    # 使用切片:将colors副本存储到new_colors
    new_colors = colors[:]  #新列表
    colors.append("black")  #原列表添加black
    new_colors.append("gray")   #新列表添加gray
    print(colors)	#打印:['red', 'green', 'blue', 'yellow', 'white', 'black']
    print(new_colors)	#打印:['red', 'green', 'blue', 'yellow', 'white', 'gray']
    
    # 直接将原列表赋给新列表
    copy_colors = colors
    colors.append("black") 
    copy_colors.append("gray")
    print(colors)	#打印:['red', 'green', 'blue', 'yellow', 'white', 'black']
    print(copy_colors)	#打印:['red', 'green', 'blue', 'yellow', 'white', 'black']
    # 让Python将新变量copy_colors关联到包含在colors中的列表,因此这两个变量都指向同一个列表。
    
  • 元组

    不可变的列表,值不可修改。元组类似于不可变的数组

    arrs = (100,200)
    print(arrs) #打印:(100,200)
    print(arrs[0])  #打印:100
    print(arrs[1])  #打印:200#尝试修改元组值
    arrs[1] = 201 #修改第2个元素值, 结果抛异常:TypeError: 'tuple' object does not support item assignment
    

    虽然不能修改元组的元素,但可以给存储元组的变量重新赋值:

    arrs = (100,200)
    print(arrs) #打印:(100,200)
    arrs = (101,201)
    print(arrs) #打印:(101,201)
    

    遍历元组中所有值(如同遍历列表:

    for arr in arrs:
        print(arr)  #打印:100   200
    

总结

  1. 列表是可变的数据集合,可以增删改;元组是不可变的,创建后元素值和顺序均不能改变;切片本身是可变的,且切片操作不影响原始列表顺序
  2. 列表常用于和存储和操作多个相关的数据项,以便动态进行增删改查; 元组则常用于固定的数据结构,如尺寸坐标数据; 切片常用于对于列表序列进行切片操作,提取指定范围内的子集元素
  3. 一般列表对于性能和内存的占用较高,由于其需要额外空间来支持动态修改