• Python基础:1.数据类型(元组)


    提示:python版本为2.7,windows系统

    1.元组(Tuple)

      Tuple,与List类似,但是Tuple一旦初始化之后就不能修改了,没有增加、删除、修改元素。

    1 >>> colors = ('red', 'orange', 'yello')
    2 >>> colors
    3 ('red', 'orange', 'yello')
    4 >>> type(colors)
    5 <type 'tuple'>

      空元组

    1 >>> color = ()
    2 >>> color
    3 ()

      1个元素

    1 >>> color = (1)      #这和数学的小括号一样,所以当只有一个元素时,在末尾要加逗号
    2 >>> color
    3 1
    4 >>> color = (1,)     #是这种
    5 >>> color
    6 (1,)

     修改元素,不能修改,也没有添加、删除方法

    1 >>> colors[0] = 'white'
    2 
    3 Traceback (most recent call last):
    4   File "<pyshell#18>", line 1, in <module>
    5     colors[0] = 'white'
    6 TypeError: 'tuple' object does not support item assignment

      其他与List类似

     1 >>> colors[0]
     2 'red'
     3 >>> colors[-1]
     4 'yello'
     5 >>> colors[0:1]
     6 ('red',)
     7 >>> colors[-1:-2]
     8 ()
     9 >>> colors[-1:]
    10 ('yello',)
    11 >>> colors[-1:1]
    12 ()
    13 >>> colors[-1:-1]
    14 ()
    15 >>> colors[-2:-1]
    16 ('orange',)
    17 >>> colors[-3:-2]
    18 ('red',)

      当元组中有List时

     1 >>> test = ('a', 'b', 'c', ['d', 'e', 'f'])
     2 >>> test[3]
     3 ['d', 'e', 'f']
     4 >>> type(test[3])
     5 <type 'list'>
     6 >>> test[3] = ['d']      #并不能修改List
     7 
     8 Traceback (most recent call last):
     9   File "<pyshell#38>", line 1, in <module>
    10     test[3] = ['d']
    11 TypeError: 'tuple' object does not support item assignment
    12 
    13 #可以修改List的元素
    14 >>> test[3][0] = 'g'
    15 >>> test[3][1] = 'h'
    16 >>> test[3][2] = 'i'
    17 >>> test
    18 ('a', 'b', 'c', ['g', 'h', 'i'])
    19 #删除List元素
    20 >>> test[3].pop()
    21 'i'
    22 >>> test
    23 ('a', 'b', 'c', ['g', 'h'])

      其实,Tuple的不能修改是指每个元素的指向地址不变,指向'red'后不能改成指向'white',指向List时,List不能变成其他元素,但是List中的元素可以改变

  • 相关阅读:
    influxdb 使用
    【刷题】如何查找最长链
    学习中的开源框架和系统
    常见错误总结
    开发者必备网站
    计算机基础知识以及常用业务场景
    (1)、hive框架搭建和架构简介
    hadoop安装和配置
    linux基础
    UML学习目录
  • 原文地址:https://www.cnblogs.com/imeng/p/5050582.html
Copyright © 2020-2023  润新知