• 7.元组


    元组元素用小括号()包裹,不可以更改(尽管他们的内容可以)

    元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可

    可以认为元组是"静态"的列表
    元组一旦定义,不能改变

    1、创建元组

    1.通过()或工厂函数tuple()创建元组
    2.元组是有序的、不可变类型
    3.与列表类似,作用于列表的操作,绝大数也可以作用于元组

    aTuple = ('one', 'two', 'three')
    bTuple = tuple(['hello', 'world'])
    print aTuple,bTuple

    执行结果:

    ('one', 'two', 'three') ('hello', 'world')

    2、元组操作符

    1.由于元组也是序列类型、所以可以作用在序列上的操作都可以作用于元组
    2. 通过in、not in判断成员关系

    >>> print bTuple
    ('hello', 'world')
    >>> 'hello' in bTuple
    True

    3、元组特性

    1.创建空元组

    a = ();

    2.单元素元组

     如果一个元组中只有一个元素,那么创建该元组的时候,需要加上一个逗号

     
    >>> cTuple = ('hello')
    >>> print cTuple
    hello
    >>> type(cTuple)
    <type 'str'>
    >>> dTuple = ('hello',)
    >>> print dTuple
    ('hello',)
    >>> type(dTuple)
    <type 'tuple'>
     

    3."更新"元组

    虽然元组本身是不可变的,但是因为它同时属于容器类型,也就意味着元组的某一个元素是可变的容器类型,那么这个元素中的项目仍然可变

     
    >>> aTuple = ('bob',['apple', 'cat'])
    >>> aTuple[0] = 'tom'
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
    >>> aTuple[1][1] = 'dog' >>> print aTuple ('bob', ['apple', 'dog'])
     

    4、元组内置函数

    Python元组包含了以下内置函数

    序号方法及描述
    1 cmp(tuple1, tuple2)
    比较两个元组元素。
    2 len(tuple)
    计算元组元素个数。
    3 max(tuple)
    返回元组中元素最大值。
    4 min(tuple)
    返回元组中元素最小值。
    5 tuple(seq)
    将列表转换为元组。
     
    >>> t = (11,22,33)
    >>> t.count(11)
    1
    >>> t.index(22)
    1
    >>> 
     

    十五,写代码,有如下元组,请按照功能要求实现每一个功能

    tu = ('alex','eric,'rain')

      1,计算元组的长度并输出

      2,获取元祖的第二个元素,并输出

      3,获取元祖的第1-2个元素,并输出

      4,请用for输出元祖的元素

      5,请使用for,len,range输出元组的索引

      6,请使用enumerate输出元组元素和序号,(从10开始)

    具体实现:

    #!/usr/bin/env python
    #coding:utf-8
    
    tu = ('alex','eric','rain')
    # 1,计算元组的长度并输出
    print(len(tu))
    
    # 2,获取元祖的第二个元素,并输出
    print(tu[1])
    
    #3,获取元祖的第1-2个元素,并输出
    print(tu[0:2])
    
    #4,请用for输出元祖的元素
    for i in tu:
        print(i)
    
    #5,请使用for,len,range输出元组的索引
    for i in range(len(tu)):
        print(i)
    
    # 6,请使用enumerate输出元组元素和序号,(从10开始)
    for index,i in enumerate(tu,10):
        print(index,i)

    执行结果:

    3
    eric
    ('alex', 'eric')
    alex
    eric
    rain
    0
    1
    2
    (10, 'alex')
    (11, 'eric')
    (12, 'rain')
  • 相关阅读:
    linq to sql 还没解决的问题
    js暂停函数,想做牛人的菜鸟遇到了问题。
    公司给我拿800/月 干不干啊?ASP.NET程序员
    android の Handler消息传递机制
    android の Activity & View | LayoutInflate
    ActionScript事件侦听addEventListener的参数详解
    java中String的intern方法和equals方法的使用
    java中short,int转换成byte数组及byte数组转换成short,int
    Flex组件中list里面的数据引用
    Flex中设置弹出窗口的弹出效果(alpha值的渐变和scale值的渐变)
  • 原文地址:https://www.cnblogs.com/zhongguiyao/p/11048143.html
Copyright © 2020-2023  润新知