Exercise_13

Exercise 13 : Tuple

Test :

  1. 列表:一个大仓库,可以随时往里面添加和删除任何东西。

    元组:封闭的列表,一旦定义,就不可改变。

  2. 当内容需要不能轻易被改写,使用元组

    反之,频繁修改数据的话,使用列表

  3. 元组可以使用的内置方法 (?)

  4. 拼接只有一个元素的元组时,逗号和小括号必须同时存在

  5. 所有多对象的、逗号分隔的、没有明确用符号定义的这些集合默认的类型都是元组。

    1
    2
    3
    4
    5
    >>> h = x, y, z = 1, 2, 3
    >>> type(x)
    <class 'int'>
    >>> type(h)
    <class 'tuple'>
  6. 元组推导式/元组解析

    不存在元组推导式,会变成生成器/类似于迭代器

    1
    2
    3
    >>> tuple1 = (x**2 for x in range(5))
    >>> type(tuple1)
    <class 'generator'>

    python3中next()改为__next__()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    >>> tuple1 = (x**2 for x in range(8))
    >>> tuple1.__next__()
    0
    >>> tuple1.__next__()
    1
    >>> tuple1.__next__()
    4
    >>> tuple1.__next__()
    9
    >>> tuple1.__next__()
    16
    >>> tuple1.__next__()
    25
    >>> tuple1.__next__()
    36
    >>> tuple1.__next__()
    49
    >>> tuple1.__next__()
    Traceback (most recent call last):
    File "<pyshell#9>", line 1, in <module>
    tuple1.__next__()
    StopIteration

    相当于在迭代中输出元素


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!