zoukankan      html  css  js  c++  java
  • 列表-元组(tuple)

    1.创建和访问元组

    >>> temp = (1,2,3,4,5,6)
    >>> temp[1]
    2
    >>> temp[5:]
    (6,)
    >>> temp[2:]
    (3, 4, 5, 6)
    >>> temp2 = temp[1:]
    >>> temp2
    (2, 3, 4, 5, 6)
    

      元组的访问同列表一样

    2.元组不能被修改

    >>>temp[1] = 9
    Traceback (most recent call last):
      File "<pyshell#9>", line 1, in <module>
        temp[1] = 9
    TypeError: 'tuple' object does not support item assignment
    

      

    3.使用小括号创建的变量一定是元组吗?答案不是!

    >>> temp3 = (1)
    >>> type(temp3)
    <class 'int'>
    

    4.那怎样创建才是元组呢?

    >>> temp4 = (1,)
    >>> type(temp4)
    <class 'tuple'>
    >>> 
    

     使用分隔符的前提下,不适用括号也能创建元组。

    >>> temp3 = 1,
    >>> type(temp3)
    <class 'tuple'>

     可知创建元组必须使用逗号分隔,即使创建只有一个元素的元组也需要使用 ','分割,tuple在Python中指元组。

    5.常出的笔试题

    >>> 8 * (8)
    64
    >>> 8 * (8,)
    (8, 8, 8, 8, 8, 8, 8, 8)
    

    6.更新和删除一个元组,刚才讲过元组不能被修改,但是为什么又要讲更新和删除呢?虽然不能使用索引的方式修改元组,但是Python允许使用切片的方式对元组进行更新删除操作。

    >>> temp = ('张三', '李四', '王二')
    >>> temp = temp[:2] + ['麻子',] + tepm[:2]
    Traceback (most recent call last):
      File "<pyshell#19>", line 1, in <module>
        temp = temp[:2] + ['麻子',] + tepm[:2]
    TypeError: can only concatenate tuple (not "list") to tuple
    >>> temp = temp[:2] + ('麻子',) + temp[:2]
    >>> temp
    ('张三', '李四', '麻子', '张三', '李四')
    >>>
    

      虽然元组可以按照列表的方式访问数组,但是在进行运算的时候,各变量类型必须一致。

    7.元组相关操作符

      拼接操作符:+ 

      参与运算的数据类型必须一致

      重复操作符: *

      等等。

      

  • 相关阅读:
    codevs 3115 高精度练习之减法 swap
    codevs 3116 高精度练习之加法
    poj 3984 迷宫问题
    codevs m进制转化成10进制
    codevs 1214 线段覆盖
    codevs 3143 二叉树的序遍历
    codevs 3145 汉诺塔
    HDU 5093 Battle ships [二分图匹配]
    HDU 5074 Hatsune Miku [dp] ——2014鞍山现场赛E题
    ZOJ 3793 First Digit (逗比题)
  • 原文地址:https://www.cnblogs.com/xiangdongsheng/p/13414212.html
Copyright © 2011-2022 走看看