zoukankan      html  css  js  c++  java
  • Python 操作列表

    1 遍历列表元素

    colors = ["red","blue","yellow","orange","white","pink","brown"]
    for color in colors :
        print(color)

     2 使用range()创建数值列表

    # 使用range创建数值列表
    numbers = list(range(1, 11))  # range不包括最后一个值
    print(numbers)
    
    # 指定步长,可创建基数或者偶数数值列表
    numbers = list(range(2, 11, 2))
    print(numbers)
    numbers = list(range(1, 11, 2))
    print(numbers)
    
    # 使用**(乘方)创建乘方列表
    squares = []
    for value in range(1, 11):
        squares.append(value**2)
    print(squares)

    3 数值列表中最大值,最小值

    squares = []
    for value in range(1, 11):
        squares.append(value**2)
    print(squares)
    # 列表中最大值
    print(max(squares))
    # 列表中最小值
    print(min(squares))

    4 使用列表解析创建列表

    squares = [value**2 for value in range(1, 11)]
    print(squares)
    # 说明:指定一个表达式(value**2),写一个for循环,用于给表达式提供值

    5 使用列表的一部分(切片)

    # 指定第一个元素索引和最后一个元素索引+1
    colors = ["red", "blue", "yellow", "orange", "white", "pink", "brown"]
    print(colors[1:4])
    
    # 没有指定第一个索引,从列表开头开始
    print(colors[:4])
    
    # 没有指定最后索引,截止到列表最后一个元素
    print(colors[4:])
    
    # 截取列表后3个元素
    print(colors[-5:])
    
    # 遍历切片
    for color in colors[-3:]:
        print(color)

    6 复制列表

    # 如果单纯的给一个变量赋值,并没有复制列表,两个变量指向同一个列表
    colors = ["red", "blue", "yellow", "orange", "white", "pink", "brown"]
    colors_copy = colors
    colors_copy.append("green")
    print(colors) # colors列表也发生变化了
    
    # 使用切片复制列表
    colors_copy = colors[:]
    colors_copy.append("black")
    print(colors)
    print(colors_copy)

    7 不可变列表(元组)

    # 定义元组,使用圆括号而不是方括号
    colors = ("red", "blue", "yellow", "orange", "white", "pink", "brown")
    print(colors[1])
    
    # 如果修改元组中的元素,将返回类型错误信息
    colors[0] = "black"
    # 错误信息:TypeError: 'tuple' object does not support item assignment
    
    # 但可以给元组变量重新赋值,达到修改元组的目的
    colors = ("red", "blue")
    print(colors)
  • 相关阅读:
    Codeforces 590 A:Median Smoothing
    HDU 1024:Max Sum Plus Plus 经典动态规划之最大M子段和
    POJ 1027:The Same Game 较(chao)为(ji)复(ma)杂(fan)的模拟
    【算法学习】 在一天的24小时之中,时钟的时针、分针和秒针完全重合在一起的时候有几次?
    【读书笔记】 spinlock, mutex and rwlock 的性能比较
    【读书笔记】 nginx 负载均衡测试
    【读书笔记】 多线程程序常见bug
    关注一下 hurd OS的开发
    【读书笔记】 分布式文件存储系统 MogileFS
    【读书笔记】 nginx + memcached 高速缓存
  • 原文地址:https://www.cnblogs.com/liyunfei0103/p/10146633.html
Copyright © 2011-2022 走看看