• python--操作列表


    上一篇我们介绍了列表的基本内容,包括如果创建列表、如何操作列表中元素,本篇内容我们将学习如何遍历列表并且在循环过程中处理某些操作
    1、遍历整个列表

    def print_hi():
        magicians = ['alice','david','carolina']
        for magician in  magicians:
            print(magician)
    
    • 1
    • 2
    • 3
    • 4

    输出

    alice
    david
    carolina
    
    • 1
    • 2
    • 3

    2、在for循环中执行更多操作
    例如在下面示例中我们打印每一个魔术师名次,并打印一些描述信息

    def print_hi():
        magicians = ['alice','david','carolina']
        for magician in magicians:
            print(magician.title() + ", that was a great trick!")
            print("I can't wait to see your next trick, "+magician.title()+"\n")
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出

    Alice, that was a great trick!
    I can't wait to see your next trick, Alice
    
    David, that was a great trick!
    I can't wait to see your next trick, David
    
    Carolina, that was a great trick!
    I can't wait to see your next trick, Carolina
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    3、在for循环结束后执行某些操作
    描述:在for循环后面,没有缩进的代码都只执行一次,而不会重复执行
    用处:在for循环结束后需要提供总结性输出或接着执行程序必须完成的其他任务使用。
    示例:

    def print_hi():
        magicians = ['alice','david','carolina']
        for magician in magicians:
            print(magician.title() + ", that was a great trick!")
            print("I can't wait to see your next trick, "+magician.title()+"\n")
        print("Thank you,everyone,That was a great magic show!")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    输出

    Alice, that was a great trick!
    I can't wait to see your next trick, Alice
    
    David, that was a great trick!
    I can't wait to see your next trick, David
    
    Carolina, that was a great trick!
    I can't wait to see your next trick, Carolina
    
    Thank you,everyone,That was a great magic show!
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    提示

    1、for循环中不要遗漏冒号
    2、该缩进的时候缩进,避免异常出输出和错误

    4、创建数值列表
    (1)使用range()方法生成一系列数字的列表,函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止,示例如下

    def print_hi():
        for value in range(1,5):
            print(value)
    
    • 1
    • 2
    • 3

    输出

    1
    2
    3
    4
    
    • 1
    • 2
    • 3
    • 4

    (2)使用range()方法创建数字列表
    将range()作为list()的参数,输出将为一个数字列表,其本质是使用list()将range()的结果转换为列表。
    示例1:

    def print_hi():
        numbers = list(range(1,6))
        print(numbers)
    
    • 1
    • 2
    • 3

    输出

    [1, 2, 3, 4, 5]
    
    • 1

    示例2:指定range()的步长,例如创建10以内偶数列表

    def print_hi():
        numbers = list(range(2,11,2))
        print(numbers)
    
    • 1
    • 2
    • 3

    输出

    [2, 4, 6, 8, 10]
    
    • 1

    示例3:如何创建一个列表,其中包含前
    10个整数(即1~10)的平方呢?在Python中,两个星号(**)表示乘方运算

    def print_hi():
        squares = []
        for value in range(1,11):
            square = value**2
            squares.append(square)
    
        print(squares)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    输出

    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    • 1

    总结:使用函数range()几乎能够创建任何需要的数字集,只需要我们更改range()方法的参数,并且在for循环中加入某些操作
    3、对数字列表的统计
    我们这里简单列出几个常用的方法min、max、sum,看下面示例

    def print_hi():
        digits = list(range(0,10,1))
        print(digits)
        print(min(digits))
        print(max(digits))
        print(sum(digits))
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    输出

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    0
    9
    45
    
    • 1
    • 2
    • 3
    • 4

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

    def print_hi():
        squares = [value**2 for value in range(1,11)]
        print(squares)
    
    • 1
    • 2
    • 3

    输出

    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    • 1

    6、使用列表的一部分–切片
    (1)切片–使用[],并且在方括号内指定使用的第一个元素和最后一个元素的索引(不包括最后一个元素),中间用分号分隔,要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为0、1和2的元素。
    示例1

    players = ['charles','martina','michael','florence','eli']
        print(players[0:3])
    
    • 1
    • 2

    输出

    ['charles', 'martina', 'michael']
    
    • 1

    示例2:没有指定第一个索引,Python将自动从列表开头开始。

    def print_hi():
        players = ['charles','martina','michael','florence','eli']
        print(players[:4])
    
    • 1
    • 2
    • 3

    输出

    ['charles', 'martina', 'michael', 'florence']
    
    • 1

    示例3:获取列表指定索引后面的元素

    • 方式一:从指定索引开始终止于列表末尾
    def print_hi():
        players = ['charles','martina','michael','florence','eli']
        print(players[2:])
    
    • 1
    • 2
    • 3

    输出

    ['michael', 'florence', 'eli']
    
    • 1
    • 方式二:负数索引返回离列表末尾相应距离的元素
    def print_hi():
        players = ['charles','martina','michael','florence','eli']
        print(players[-3:])
    
    • 1
    • 2
    • 3

    输出

    ['michael', 'florence', 'eli']
    
    • 1

    (2)遍历切片
    场景:如果要遍历列表中的部分元素时,使用切片和for循环来实现,示例如下

    def print_hi():
        players = ['charles','martina','michael','florence','eli']
        print("Here are the first three players on my team:")
        for player in players[:3]:
            print(player.title())
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出

    Here are the first three players on my team:
    Charles
    Martina
    Michael
    
    • 1
    • 2
    • 3
    • 4

    (3)复制列表

    • 使用切片,创建一个包含整个列表的切片(同时省略起始索引和终止索引([:])),即复制列表,示例如下
    def print_hi():
        my_foods = ['pizza','falafel','carrot cake']
        friend_foods = my_foods[:]
        friend_foods.append('ice cream')
    
        print("My favorite foods are:")
        print(my_foods)
    
        print("\n My friends's favorite foods are:")
        print(friend_foods)
    输出
    
    ```python
    My favorite foods are:
    ['pizza', 'falafel', 'carrot cake']
    
     My friends'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
    • 18

    分析:我们使用切片复制列表之后,使用append方法在新的列表追加元素,原列表my_foods中内容没有改变,而复制的friend_foods列表内容改变了。
    很多人有可能会 friend_foods = my_foods,但这是行不通的,这样做只是让Python将新变量friend_foods关联到my_foods中的列表中,我们改一下程序,在看输出结果

    def print_hi():
        my_foods = ['pizza','falafel','carrot cake']
        friend_foods = my_foods
        friend_foods.append('ice cream')
    
        print("My favorite foods are:")
        print(my_foods)
    
        print("\n My friends's favorite foods are:")
        print(friend_foods)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    输出

    My favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'ice cream']
    
     My friends's favorite foods are:
    ['pizza', 'falafel', 'carrot cake', 'ice cream']
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    gitlab与github 密钥冲突
    【从零开始学微服务】03.软件架构的演化过程
    Keras中stateful的正确理解
    归并排序和非比较排序
    关于2023年下半年计算机技术与软件专业技术资格(水平)考试报名工作有关事项的通知
    微信群发工具,纯Python编写~
    C++左值右值完美转发转移
    Springboot毕设项目基于Springboot的手机电商网站lmo47(java+VUE+Mybatis+Maven+Mysql)
    七夕节,我用代码制作了表白信封
    运维10个知识和经验
  • 原文地址:https://blog.csdn.net/u011774517/article/details/127984282