• python编程从入门到实践2——列表


    2. 列表介绍

    2.1 列表是什么

    用方括号([] )来表示列表,并用逗号来分隔其中的元素。列表 由一系列按特定顺序排列的元素组成。你可以创建包含字母表中所有字母、数字。

    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    print(bicycles)
    
    # ['trek', 'cannondale', 'redline', 'specialized']
    
    • 1
    • 2
    • 3
    • 4

    2.1.1 访问列表元素

    只需将该元素的位置索引告诉Python即可。

    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    print(bicycles[0])
    
    # trek
    
    # 可使用方法title() 让元素'trek' 的格式更整洁:
    print(bicycles[0].title())
    
    # Trek
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    2.1.2 索引从0而不是1开始

    第一个列表元素的索引为0

    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    print(bicycles[1])
    print(bicycles[3])
    
    # cannondale
    # specialized
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    将索引指定为 -1 ,可让Python返回最后一个列表元素

    bicycles = ['trek', 'cannondale', 'redline', 'specialized']
    print(bicycles[-1])
    
    # specialized
    
    • 1
    • 2
    • 3
    • 4

    2.2 修改、添加和删除元素

    2.2.1 修改列表元素

    motorcycles = ['honda', 'yamaha', 'suzuki'] 
    print(motorcycles)
    # ['honda', 'yamaha', 'suzuki'] 
    
    motorcycles[0] = 'ducati' 
    print(motorcycles)
    # ['ducati', 'yamaha', 'suzuki'] 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2.2.2 在列表中添加元素

    1. 在列表末尾添加元素
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    # ['honda', 'yamaha', 'suzuki']
    
    motorcycles.append('ducati') 
    print(motorcycles)
    
    # ['honda', 'yamaha', 'suzuki', 'ducati']
    
    motorcycles2 = []
    
    motorcycles2.append('honda')
    motorcycles2.append('yamaha')
    motorcycles2.append('suzuki')
    
    print(motorcycles2)
    # ['honda', 'yamaha', 'suzuki', 'ducati']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    1. 在列表中插入元素
    motorcycles = ['honda', 'yamaha', 'suzuki']
    
    motorcycles.insert(0, 'ducati')print(motorcycles)
    # ['ducati', 'honda', 'yamaha', 'suzuki']
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.2.3 从列表中删除元素

    1. 使用del 语句删除元素,删除后,你就无法再访问它了。
    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    # ['honda', 'yamaha', 'suzuki']
    
    del motorcycles[0] 
    print(motorcycles)
    # ['yamaha', 'suzuki']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    del 可删除任何位置处的列表元素,条件是知道其索引。

    motorcycles = ['honda', 'yamaha', 'suzuki']
    print(motorcycles)
    
    del motorcycles[1]
    print(motorcycles)
    
    # ['honda', 'yamaha', 'suzuki']
    # ['honda', 'suzuki']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    1. 使用方法pop() 删除末尾元素

    方法pop() 可删除列表末尾的元素,并让你能够接着使用它。术语弹出 (pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

    motorcycles = ['honda', 'yamaha', 'suzuki'] 
    print(motorcycles)
    
    popped_motorcycle = motorcycles.pop() 
    print(motorcycles) 
    print(popped_motorcycle) 
    
    # ['honda', 'yamaha', 'suzuki']
    # ['honda', 'yamaha']
    # suzuki
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    motorcycles = ['honda', 'yamaha', 'suzuki']
    
    last_owned = motorcycles.pop()
    print("The last motorcycle I owned was a " + last_owned.title() + ".")
    
    # The last motorcycle I owned was a Suzuki.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. 弹出列表中任何位置处的元素
      pop()+索引
    motorcycles = ['honda', 'yamaha', 'suzuki']
    
    first_owned = motorcycles.pop(0)print('The first motorcycle I owned was a ' + first_owned.title() + '.')
    
    # The first motorcycle I owned was a Honda.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. 根据值删除元素

    方法remove()

    motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
    print(motorcycles)
    
    motorcycles.remove('ducati') 
    print(motorcycles)
    
    # ['honda', 'yamaha', 'suzuki', 'ducati']
    # ['honda', 'yamaha', 'suzuki']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']print(motorcycles)
    
    too_expensive = 'ducati' ❷
    motorcycles.remove(too_expensive)print(motorcycles)
    print("\nA " + too_expensive.title() + " is too expensive for me.") # \n 回车
    
    # ['honda', 'yamaha', 'suzuki', 'ducati']
    # ['honda', 'yamaha', 'suzuki']
    
    # A Ducati is too expensive for me.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.3 组织列表

    2.3.1 使用方法sort() 对列表进行 永久性排序

    sort(),永久性地修改了列表元素的排列顺序。

    cars = ['bmw', 'audi', 'toyota', 'subaru']
    cars.sort()print(cars)
    
    # ['audi', 'bmw', 'subaru', 'toyota']
    
    • 1
    • 2
    • 3
    • 4
    • 5

    相反的顺序,向sort() 方法传递参数reverse=True

    cars = ['bmw', 'audi', 'toyota', 'subaru']
    cars.sort(reverse=True)
    print(cars)
    
    # ['toyota', 'subaru', 'bmw', 'audi']
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.3.2 使用函数sorted() 对列表进行 临时排序

    调用函数sorted() 后,列表元素的排列顺序并没有变。如果你要按与字母顺序相反的顺序显示列表,也可向函数sorted() 传递参数reverse=True

    cars = ['bmw', 'audi', 'toyota', 'subaru']
    
    print("Here is the original list:")print(cars)
    
    print("\nHere is the sorted list:")print(sorted(cars))
    
    print("\nHere is the original list again:")print(cars)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    output:

    Here is the original list:
    ['bmw', 'audi', 'toyota', 'subaru']
    
    Here is the sorted list:
    ['audi', 'bmw', 'subaru', 'toyota']  # 临时排序
    
    Here is the original list again:['bmw', 'audi', 'toyota', 'subaru']  # 原始顺序
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.3.3 倒着打印列表

    reverse() ,永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可。

    cars = ['bmw', 'audi', 'toyota', 'subaru']
    print(cars)
    
    cars.reverse()
    print(cars)
    
    # ['bmw', 'audi', 'toyota', 'subaru']
    # ['subaru', 'toyota', 'audi', 'bmw']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.3.4 确定列表的长度

    len()

    >>> cars = ['bmw', 'audi', 'toyota', 'subaru']
    >>> len(cars)
    4
    
    • 1
    • 2
    • 3

    3. 操作列表

    3.1 遍历整个列表

    for循环

    magicians = ['alice', 'david', 'carolina']for magician in magicians:print(magician) ❸
    
    alice
    david
    carolina
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.2 创建数值列表

    3.2.1 使用函数range()

    for value in range(1,5):
        print(value)
    # 输出
    1
    2
    3
    4
    
    for value in range(1,6):
        print(value)
    1
    2
    3
    4
    5
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    3.2.2 使用range() 创建数字列表

    numbers = list(range(1,6))
    print(numbers)
    
    # [1, 2, 3, 4, 5]
    
    even_numbers = list(range(2,11,2))
    print(even_numbers)
    
    # [2, 4, 6, 8, 10]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3.2.3 对数字列表执行简单的统计计算

    >>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    >>> min(digits)
    0
    
    >>> max(digits)
    9
    
    >>> sum(digits)
    45
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3.2.4 列表解析

    列表解析 将for 循环和创建新元素的代码合并成一行,并自动附加新元素。

    squares = [value**2 for value in range(1,11)]
    print(squares)
    
    # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    • 1
    • 2
    • 3
    • 4

    3.3 使用列表的一部分

    3.3.1 切片

    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[0:3])['charles', 'martina', 'michael']
    
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[1:4])
    ['martina', 'michael', 'florence']
    
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[:4])
    ['charles', 'martina', 'michael', 'florence']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    players = ['charles', 'martina', 'michael', 'florence', 'eli']
    print(players[-3:])
    ['michael', 'florence', 'eli']
    print(players[-3: -1])
    ['michael', 'florence']
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3.3.2 复制列表

    要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:] )。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。

    my_foods = ['pizza', 'falafel', 'carrot cake'] ❶
    friend_foods = my_foods[:]print("My favorite foods are:")
    print(my_foods)
    
    print("\nMy friend's favorite foods are:")
    print(friend_foods)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    输出:

    My favorite foods are:
    ['pizza', 'falafel', 'carrot cake']
    
    My friend's favorite foods are:
    ['pizza', 'falafel', 'carrot cake']
    
    • 1
    • 2
    • 3
    • 4
    • 5

    另外

    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("\nMy friend's favorite foods are:")
    print(friend_foods)
    
    # My favorite foods are:
    # ['pizza', 'falafel', 'carrot cake', 'cannoli'] ❹
    
    # My friend's favorite foods are:
    # ['pizza', 'falafel', 'carrot cake', 'ice cream'] ❺
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    错误方法:

    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("\nMy friend's favorite foods are:")
    print(friend_foods)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    输出:

    My favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
    
    My friend's favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
    
    • 1
    • 2
    • 3
    • 4
    • 5

    4. 其它功能

    4.1 获取指定元素的索引

    方法一: 利用数组自身的特性 a.index(target), 其中 a 是你的目标 listtarget 是你需要的下标对应的值

    a=[72, 56, 76, 84, 80, 88]
    print(a.index(76))
    
    output:
    2
    
    • 1
    • 2
    • 3
    • 4
    • 5

    但是,如果 a 中有多个 76 呢?

    方法二: 利用 enumerate 函数。
    在这里插入图片描述
    enumerate 的输出类型是 tuple!tuple!tuple! 所以,我们可以如下
    在这里插入图片描述
    列表中有重复元素时:
    在这里插入图片描述

    4.2 列表元素的频次

    求出列表lists中每个元素出现的次数

    方法一:使用函数Counter,可以迅速获取list中每个元素出现的次数
     
    from collections import Counter
    arr=[1,2,5,1,1,5,6,3,3,2,2,4,8]
    # arr=Counter(lists)
    # print(arr)
    def counter(arr):
        return Counter(arr)
    print(counter(arr))  
    # 两种写法的结果都是Counter({1: 3, 2: 3, 5: 2, 3: 2, 6: 1, 4: 1, 8: 1})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    参考链接

    [1] Python统计一个列表中每个元素出现的次数。四种方法,总有一款适合你 2019-01-10;

  • 相关阅读:
    倒计时5天!飞桨AI Studio星河社区x智海Mo AI大模型创意应用大赛等你来战!
    党建在线虚拟展厅3d展示实现视觉震撼体验和互动教育
    解释Java中的安全模型
    redhat环境ansible自动化部署
    【深度学习】树莓派Zero w深度学习模型Python推理
    【AWS SMB】关于AWS 中小型企业 (SMB) 能力介绍及注意事项
    求求并行不要寄
    【JavaScript】面试手撕节流
    百度首个江苏智算中心落地 携手盐城共建200P算力规模
    Linux—软件管理
  • 原文地址:https://blog.csdn.net/weixin_46713695/article/details/128172476