zoukankan      html  css  js  c++  java
  • py3学习笔记3(列表)

      Python可以分辨一堆不同的复合数据类型,并可以将他们整合在一起。列表(list)就是一种非常出色的方法。它可以用方括号将将一堆以逗号分隔的项整合在一起。可以包含不同的数据类型,但日常使用时常用相同的数据类型。

    >>> squares = [1, 4, 9, 16, 25]
    >>> squares
    [1, 4, 9, 16, 25]

       跟所有的内置序列类型一样(built-in sequence type),对list可以执行索引(index)和切片(slice)操作

    >>> squares[0] # indexing returns the item
    1
    >>> squares[-1]
    25
    >>> squares[-3:] # slicing returns a new list
    [9, 16, 25]

      所有的slice操作都将返回一个操作后的新list。list也支持像串接( concatenation)的操作

    >>> squares + [36, 49, 64, 81, 100]
    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

      list不像string,它是可变的(mutable),可以改变其中的内容

    >>> cubes = [1, 8, 27, 65, 125] # something's wrong here
    >>> 4**3 # the cube of 4 is 64, not 65!
    64
    >>> cubes[3] = 64 # replace the wrong value
    >>> cubes
    [1, 8, 27, 64, 125]

      你也可以使用append()方法在list的末尾添加新的项

    >>> cubes.append(216) # add the cube of 6
    >>> cubes.append(7**3) # and the cube of 7
    >>> cubes
    [1, 8, 27, 64, 125, 216, 343]

      使用slice方法对list进行操作时,可以改变list的大小甚至清空

    >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> letters
    ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    >>> # replace some values
    >>> letters[2:5] = ['C', 'D', 'E']
    >>> letters
    ['a', 'b', 'C', 'D', 'E', 'f', 'g']
    >>> # now remove them
    >>> letters[2:5] = []
    >>> letters
    ['a', 'b', 'f', 'g']
    >>> # clear the list by replacing all the elements with an empty list
    >>> letters[:] = []
    >>> letters
    []

      内置函数len()也同样适用于list

    >>> letters = ['a', 'b', 'c', 'd']
    >>> len(letters)
    4

      将list作为项整合为list也是可行的

    >>> a = ['a', 'b', 'c']
    >>> n = [1, 2, 3]
    >>> x = [a, n]
    >>> x
    [['a', 'b', 'c'], [1, 2, 3]]
    >>> x[0]
    ['a', 'b', 'c']
    >>> x[0][1]
    'b'
  • 相关阅读:
    Zookeeper系列(二)特征及应用场景
    Scala学习笔记(三)类层级和特质
    zookeeper系列(一)安装
    Scala学习笔记(二)表达式和函数
    Spring笔记(四)SpingAOP
    Spring笔记(三)AOP前篇之动态代理
    Scala学习笔记(一)数据类型
    Linux内核系列设备模型(一) Kobject与Kset
    Spring笔记(二)Core层
    Linux内核系列之Block块层(一)
  • 原文地址:https://www.cnblogs.com/jzl123/p/5864375.html
Copyright © 2011-2022 走看看