zoukankan      html  css  js  c++  java
  • think python 第12章 tuples

    12.1tuples are immutable

     创建元组的关键是使用‘,’,要创建只含一个元素的元组,需要包含最后的逗号。

    创建元组的另一个方法是使用内置函数tuple。没有参数时,创建一个空元组。

    如果参数是一个序列(字符串、列表或元组),返回结果是使用序列中的元素构成的元组。

    大多数的列表运算符适用于元组。括号运算可以索引一个元素。也可以使用切片。

    但是元组中的元素是不可修改的,我们可以使用另一个元组代替原来的元组

    12.2tuple assignment

    >>> #如果对两个元组交换赋值,不需要中间变量
    >>> a = 1,
    >>> b = 2,
    >>> a,b = b,a
    >>> print(a,b)
    (2,) (1,)
    >>> #如果我们项分离一个元组为两个元组,可以在后面使用split函数
    >>> addr = '12345678@qq.com'
    >>> qq,domain = addr.split('@')
    >>> print (qq)
    12345678
    >>> print(domain)
    qq.com

    12.3tuples as return values

    元组作为返回值时,可以返回多个值

    >>> def min_max(t):
        return min(t),max(t)
    
    >>> t = 1,2,3,4,5
    >>> print(min_max(t))
    (1, 5)
    >>> min1,max1 = min_max(t)
    >>> min1
    1
    >>> max1
    5

    12.4variable-length argument tuples

    >>> #以*开头的参数将参数聚集为一个元组
    >>> def printall(*agrs):
        print(agrs)
    
        
    >>> printall(1,2.0,'3')
    (1, 2.0, '3')
    >>> #于聚集(gaters)相对应的是散布(scatter)。如果一个值的序列要作为多个参数传递给一个函数,可以使用*运算符
    >>> t = (7,3)
    >>> divmod(t)
    Traceback (most recent call last):
      File "<pyshell#142>", line 1, in <module>
        divmod(t)
    TypeError: divmod expected 2 arguments, got 1
    >>> divmod(*t)
    (2, 1)

    许多内建函数可以使用变长参数元组,如min,max,但是sum不可以。我们可以构建一个sumall函数,用来接收多个参数,并返回它们的和。

    >>> min(1,2,3)
    1
    >>> max(1,2,3)
    3
    >>> sum(1,2,3)
    Traceback (most recent call last):
      File "<pyshell#146>", line 1, in <module>
        sum(1,2,3)
    TypeError: sum expected at most 2 arguments, got 3
    >>> def sumall(*t):
        return sum(t)
    
    >>> sumall(1,2,3)
    6

    12.5lists and tuples

    内建函数zip可以将多个序列zip成一个元组的列表,每个元组包含每个列表的一个元素,如果序列长度不同,结果的长度与较短的序列相同。

    python3中返回的是一个元组的迭代器,我们需要用list强制转换。

    >>> s = 'abc'
    >>> t = [0,1,2]
    >>> zip(s,t)
    <zip object at 0x000001BFD4DE2388>
    >>> print(zip(s,t))
    >>> zip('abcd','01234')
    <zip object at 0x000001BFD4E093C8>
    >>> list(zip(s,t))
    [('a', 0), ('b', 1), ('c', 2)]
    >>> list(zip('abcd','01234'))
    [('a', '0'), ('b', '1'), ('c', '2'), ('d', '3')]

    使用for循环遍历一个元组的列表

    >>> t = list(zip('abcdefg','0123456'))
    >>> for letter,number in t:
        print(letter,number)
    
        
    a 0
    b 1
    c 2
    d 3
    e 4
    f 5
    g 6
    >>> t1 = [1,2,3,4,5]
    >>> t2 = 1,2,3,4,0
    >>> def has_match(t1,t2):
        for x,y in zip(t1,t2):
            if x == y:
                return True
        return False
    
    >>> has_match(t1,t2)
    True
    >>> #可以使用enumerate内建函数来遍历一个序列中的元素和它们的下标
    >>> for index,element in enumerate('abc'):
        print(index,element)
    
        
    0 a
    1 b
    2 c

    12.6dictionaries and tuples

    >>> d = {'a':0,'b':1,'c':2}
    >>> t = d.items()#items返回的是元组的列表,与python2稍有不同,输出结果多了前面的dict_items
    >>> print(t)
    dict_items([('a', 0), ('b', 1), ('c', 2)])
    >>> d = {'a':0,'b':1,'c':2}
    >>> t = dict(d)
    >>> t
    {'a': 0, 'b': 1, 'c': 2}
    >>> #除了用元组;列表来初始化一个字典,我们还可以结合dict和zip创建字典
    >>> d = dict(zip('abc',range(3)))
    >>> d
    {'a': 0, 'b': 1, 'c': 2}

    12.7comparing tuples

    DSU模式

    Decorate 装饰序列,生成元组列表,将一个或多个排序关键字放在元素的最前面

    Sort 对元组列表排序

    Undecorate 通过从以排序的序列中抽出元素来还原

     1 def sort_by_length(words):
     2     t = []
     3     for word in words:
     4         t.append((len(word),word))
     5 
     6     t.sort(reverse=True)
     7 
     8     res = []
     9     for lengte,word in t:
    10         res.append(word)
    11     return res
    12 
    13 wo = 'hello','python','hi','world'
    14 print(sort_by_length(wo))

    12.8sequences of sequences

    列表比元组更为常用,主要因为它们是可改变的。但有一些情况我们会更倾向元组

    1.在某些情况下,如return语句,句法上创建一个元组比创建一个列表更方便。在其它情况下,我们也许更倾向列表

    2.若使用一个类似字典关键字的序列,我们必须使用类似元组或字符串的不可改变的数据类型

    3.若将序列作为函数值参数,使用元组会减少潜在的因为别名而造成的意外的行为

    由于元组是不可改变的,他们不提供类似sort或reverse等修改列表的方法。但是python提供内建函数sorted和reversed,它们读取任何序列作为参数,并返回一个新的排序后的列表

  • 相关阅读:
    ArrayList removeRange方法分析
    LinkedHashMap源码分析(基于JDK1.6)
    LinkedList原码分析(基于JDK1.6)
    TreeMap源码分析——深入分析(基于JDK1.6)
    51NOD 2072 装箱问题 背包问题 01 背包 DP 动态规划
    51 NOD 1049 最大子段和 动态规划 模板 板子 DP
    51NOD 1006 最长公共子序列 Lcs 动态规划 DP 模板题 板子
    8月20日 训练日记
    CodeForces
    CodeForces
  • 原文地址:https://www.cnblogs.com/Kingwjk/p/7922083.html
Copyright © 2011-2022 走看看