zoukankan      html  css  js  c++  java
  • 元组:困在牢笼的列表

    列表:一个大仓库,你可以随时往里边添加和删除任何东西。
    元组:封闭的列表,一旦定义,就不可改变(不能添加、删除或修改)。

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

    元组的标志性符号不是小括号,而是逗号,所以元组中只包含一个元素时,需要在元素后面添加逗号:

    >>> temp = (1)
    >>> type(temp)     #整形
    <class 'int'>
    
    >>> temp = (1,)     #或者temp = 1,
    >>> type(temp)
    <class 'tuple'>
    
    
    >>> temp = 2,3,4    #不加括号也可以
    >>> type(temp)
    <class 'tuple'>
    
    >>> temp = ()    #空元组
    >>> type(temp)
    <class 'tuple'>

    可以对元组进行操作的操作符:
    拼接操作符:+

    >>> temp = ('diss',3,5.99,-22)
    >>> temp
    ('diss', 3, 5.99, -22)
    >>> temp = temp[:2] + ("bad",) + temp[2:]
    >>> temp
    ('diss', 3, 'bad', 5.99, -22)

    重复操作符:*      

    >>> 8 * (3,)
    (3, 3, 3, 3, 3, 3, 3, 3)

    成员操作符:in/ not in

    >>> 2 in temp4
    True

    关系操作符:> <

    >>> temp5 = (4,5,6)
    >>> temp6 = (5,4,3)
    >>> temp5 > temp6
    False

    逻辑操作符:and or

    删除temp元组,但是较少使用 

    >>>del temp
    或者使用切片
    >>> temp = temp[3:]
    >>> temp
    (5.99, -22)

    元组的内置函数:
    1、比较两个元组的元素

    >>> import operator
    >>> operator.eq(temp5,temp6) False

      >>> operator.gt(temp5,temp6)
      False           #同之前比较大小的例子

      >>>help(operator)    #可查询更多用法

    计算元组元素个数:len(tuple1)

    返回元组中元素最大值:max(tuple1)
    返回元组中元素最小值:min(tuple1)
    将列表转换为元组:tuple(list)

    返回某个参数在元组中的位置:tuple.index(...)

    计算某个参数在元组中出现的次数:tuple.count(...)



  • 相关阅读:
    【poj2761】 Feed the dogs
    【bzoj1086】 scoi2005—王室联邦
    学堂在线
    【bzoj3757】 苹果树
    【uoj58】 WC2013—糖果公园
    博弈论学习笔记
    【poj2960】 S-Nim
    【poj2234】 Matches Game
    【poj1740】 A New Stone Game
    【bzoj1853】 Scoi2010—幸运数字
  • 原文地址:https://www.cnblogs.com/mumulucky/p/13485184.html
Copyright © 2011-2022 走看看