Chapter 3 - Python列表

Python列表

列表是由一系列按特定顺序排列的元素组成。

可以通过[]来定义列表:

python 复制代码
vehicles = ['car', 'airplane', 'bicyle', 'train']

如果需要访问列表中的元素,可以通过列表名称 + 元素索引的方式来访问列表元素vehicles[0],这个时候就可以访问到car字符串元素,列表的索引是从0开始而不是从1开始,与其他语言访问的区别在于Python的列表可以通过负数索引倒叙访问vehicles[-1],这个时候访问的就是train字符串元素。

列表通用操作

  • 修改:可以直接给列表中某个索引位置重新赋值修改列表元素值。

    python 复制代码
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    ​
    motorcycles[0] = 'ducati'
    print(motorcycles)

    执行结果:

  • 添加元素:

    • 列表末尾追加:可以通过append()方法向列表当中追加元素。

      python 复制代码
      motorcycles = ['honda', 'yamaha', 'suzuki']
      print(motorcycles)
      ​
      motorcycles.append('ducati')
      print(motorcycles)

      执行结果:

    • 列表中插入元素:可以使用insert()方法向列表任意位置添加元素

      python 复制代码
      motorcycles = ['honda', 'yamaha', 'suzuki']
      print(motorcycles)
      ​
      motorcycles.insert(0, 'ducati')
      print(motorcycles)

      执行结果:

  • 删除元素:

    • 使用del语句删除元素:通过这种方式可以删除任意索引的元素,但是del语句是没有返回值的,也就是说无法知道删除的是哪个元素,当通过del语句删除列表元素时,后续则无法继续使用。

      python 复制代码
      motorcycles = ['honda', 'yamaha', 'suzuki']
      print(motorcycles)
      ​
      del motorcycles[0]
      print(motorcycles)

      执行结果:

    • 使用pop({index})方法删除元素:当pop方法中无参数的时候默认删除最后一个元素,相当于把列表看作是一个堆栈,对堆栈中的元素进行出栈操作。但是当pop中的参数指定了具体的索引,就会明确指明需要删除哪个索引元素。同时pop方法是有返回值的,可以通过变量接收通过pop删除的元素,供后续代码处理使用。

      python 复制代码
      #pop方法无参的情况
      motorcycles = ['honda', 'yamaha', 'suzuki']
      print(motorcycles)
      ​
      del_motor = motorcycles.pop()
      print(motorcycles)
      print(del_motor)

      执行结果:

      python 复制代码
      #pop方法有参情况
      motorcycles = ['honda', 'yamaha', 'suzuki']
      print(motorcycles)
      ​
      del_motor = motorcycles.pop(1)
      print(motorcycles)
      print(del_motor)

      执行结果:

    • 使用remove({element})方法删除元素:如果不清楚需要删除的元素在列表中的索引位置,只知道需要删除的元素的值,可以使用remove方法。但是需要注意的是,第一点remove方法也是没有任何返回值;第二点当列表中存在多个值相同的元素的时候,remove方法只能删除从头开始第一次出现的值,如果想要全部删除,需要找到出现次数通过循环实现。

      python 复制代码
      motorcycles = ['honda', 'yamaha', 'suzuki']
      print(motorcycles)
      ​
      too_expensive = "honda"
      too_expensive_motor = motorcycles.remove(too_expensive)
      print(motorcycles)
      print(too_expensive)
      print(too_expensive_motor)

      执行结果:

      python 复制代码
      motorcycles = ['honda', 'yamaha', 'suzuki', 'honda']
      print(motorcycles)
      ​
      too_expensive = 'honda'
      too_expensive_motor = motorcycles.remove(too_expensive)
      print(motorcycles)
      print(too_expensive)
      print(too_expensive_motor)

      执行结果:

  • 列表排序

    • sort(reverse=False)排序:通过sort()方法排序会直接操作原列表,会对原列表里面的内容产生修改。还可以通过在参数里面加sort(reverse=True)翻转排序顺序。这里需要注意sort()是列表内置方法。

      python 复制代码
      cars = ['bmw', 'audi', 'toyota', 'subaru']
      cars.sort()
      print(cars)

      执行结果:

    • sorted({list}, reverse=False)排序:通过sorted()方法排序不会直接操作原列表。可以通过在参数里面加sorted({list}, reverse=True)翻转排序顺序。这里需要注意sorted()是内置函数。

      python 复制代码
      cars = ['bmw', 'audi', 'toyota', 'subaru']
      print('original list:')
      print(cars)
      ​
      cars_sorted = sorted(cars)
      print('sorted list:')
      print(cars_sorted)
      ​
      print('original list again:')
      print(cars)

      执行结果:

  • 列表翻转:

    如果想要实现列表按照当前顺序翻转输出,可以使用列表内置方法reverse()。需要注意的是reverse()是会直接对原列表发生修改。

    python 复制代码
    cars = ['bmw', 'audi', 'toyota', 'subaru']
    print(cars)
    cars.reverse()
    print(cars)

    执行结果:

  • 列表长度:可以使用内置函数len({list})来获取列表的长度。

列表相关操作

  • range(start, stop, step)函数:

    range(stop)函数表示生成0 ~ stop-1之间的数。

    range(start, stop)函数表示生成start ~ stop-1之间的数。

    range(start, stop, step)函数表示生成start ~ stop-1之间的数,且步进值为step

    python 复制代码
    print("list1 start")
    for val in range(5):
        print(val)
    print("list1 end \n")
    ​
    print("list2 start")
    for val1 in range(0, 6):
        print(val1)
    print("list2 end \n")
    ​
    print("list3 start")
    for val2 in range(0, 7, 2):
        print(val2)
    print("list3 end \n")

    执行结果:

perl 复制代码
`range`函数可以搭配`list`函数创建数值列表。

```python
numbers = list(range(5))
print(numbers)
```

执行结果:

![image-20260303140956236](https://p3-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/9895a94320ea49fba42c019fbdb19f04~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgR2lub1dp:q75.awebp?rk3s=f64ab15b&x-expires=1774257331&x-signature=T56nXoSDXclBaIBTTUO0l%2BLHgaM%3D)
  • min(list)max(list)函数:

    用于统计列表里面最大/小值。

    python 复制代码
    numbers = [9, 4, 0, 1, 3]
    print(f"The maximum value in the numerical list: {max(numbers)}")
    print(f"The minimum value in the numerical list: {min(numbers)}")
    ​
    strs = ['da', 'cs', 'agb', 'ac']
    print(f"The maximum value in the string list: {max(strs)}")
    print(f"The minimum value in the string list: {min(strs)}")

    执行结果:

  • sum(list)函数:

    用于统计数值列表的总和。

    python 复制代码
    numbers = [9, 4, 0, 1, 3]
    print(sum(numbers))

    执行结果:

  • 切片操作:

    创建切片的时候,指定要使用的第一个元素和最后一个元素的索引,可以通过这种方式生成列表中任意元素连续的子集。

    python 复制代码
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[0:3])

    执行结果:

    通过这个示例可以看出,切片获取的是列表中索引为0,1,2的三个元素,由此可知切片截取的索引范围是[start, end-1]。当切片中未指定开始索引默认从索引0开始截取;当切片为指定结束索引的时候,默认截取至索引len(list) - 1

    常见的应用场景就是我们可以通过切片操作实现列表的复制:

    python 复制代码
    my_foods = ['pizza', 'falafel', 'carrot cake']
    friend_foods = my_foods[:]
    ​
    print("My favorite foods are:")
    print(my_foods)
    ​
    print("\n My friend's favorite foods are:")
    print(friend_foods)

    执行结果:

    提到复制就必须说明一个易错点:千万不能使用my_foods = friend_foods进行复制操作,这样并不是将my_foods中的值复制给friend_foods列表,学过C语言知道这是将my_foods列表变量的地址赋值给firend_foods,当对其中一个列表变量操作的时候会同时影响到另一个变量。接下来看一个例子:

    python 复制代码
    #采用切片的方式复制列表
    my_foods = ['pizza', 'falafel', 'carrot cake']
    friend_foods = my_foods[:]
    ​
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    ​
    print("My favorite foods are:")
    print(my_foods)
    ​
    print("\n My friend's favorite foods are:")
    print(friend_foods)
    ​
    print("\n\n")
    ​
    #采用直接赋值的方式复制列表
    my_foods = ['pizza', 'falafel', 'carrot cake']
    friend_foods = my_foods
    ​
    my_foods.append('cannoli')
    friend_foods.append('ice cream')
    ​
    print("My favorite foods are:")
    print(my_foods)
    ​
    print("\n My friend's favorite foods are:")
    print(friend_foods)

    执行结果:

补充内容:

Python中有innot in关键字,可以直接判断元素是否在列表当中

python 复制代码
fruits = ['apple', 'banana', 'strawberry', 'grape', 'orange']
print('apple' in fruits)
print('watermelon' in fruits)

执行结果:

相关推荐
姚生2 小时前
Tushare全解析:金融量化分析的数据基石
大数据·python
Hi202402172 小时前
如何从互联网上免费下载歌曲
python·自动化
2401_898075122 小时前
Python在金融科技(FinTech)中的应用
jvm·数据库·python
老师好,我是刘同学2 小时前
选择排序原理与Python实现
python·排序算法
wmfglpz883 小时前
NumPy入门:高性能科学计算的基础
jvm·数据库·python
如若1233 小时前
WSL2安装Ubuntu完整教程:自定义安装目录到D盘(--location一键搞定)
linux·运维·服务器·pytorch·python·ubuntu·计算机视觉
@fai3 小时前
【Python多线程截图】当 Python 多线程遇上底层 C 库——一次由“串图”引发的线程安全深度思考
python·opencv·numpy
alvin_20054 小时前
python之OpenGL应用(五)变换
python·opengl
深蓝电商API4 小时前
服务器部署爬虫:Supervisor 进程守护
爬虫·python