美文网首页
第4章 操作列表

第4章 操作列表

作者: lkj666 | 来源:发表于2021-03-31 22:13 被阅读0次

    参考书籍:《Python编程 从入门到实践》

    1. 用for语句遍历列表

    magicians = ['alice', 'david', 'carolina']
    for magician in magicians:
        print(magician.title() + ", that was a great trick!")
        print("I cant' wait to see your next trick, " + magician.title() +".\n")
    
    print("Thank you, everyone. That was a great magic show!")
    

    注意事项:

    1. 单复数的命名方式对于遍历列表很有用
    2. 不要忘记for语句最后的冒号:
    3. 避免缩进错误,需要循环的语句都需要缩进



    2. 创建数字列表

    numbers = list(range(1,5))
    print(numbers)
    

    函数range(1,5)会生成从1到4的数字(rang()还可以指定步长值)
    函数list()函数range(1,5)生成的数字转换成列表

    • 使用举例1:创建一个列表,使其包含前10个整数的平方
    方式一:
    squares = []
    for value in range(1,11):
        square = value**2
        squares.append(square)
        print(squares)
    
    方式二:列表解析
    squares = [value**2 for value in range(1,11)]
    print(squares)
    



    3. 操作列表

    3.1 遍历切片

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

    切片时,指定第一个元素和最后一个元素的索引,在到达指定的第二个索引前面的元素后停止。

    3.2 复制列表

    my_foods = ['pizza', 'falafel', 'carrot cake']
    friend_foods = my_foos[:]
    

    [:]省略起始索引和终止索引表示整个列表

    相关文章

      网友评论

          本文标题:第4章 操作列表

          本文链接:https://www.haomeiwen.com/subject/biprhltx.html