2. 元组

tuple性质

  1. tuple是常量listtuple不能pop,remove,insert等方法
  2. tuple用()表示,如a=(0,1,2,3,4),括号可以省略
  3. tuple可以用下标返回元素或者子tuple
  4. tuple 可以用于多个变量的赋值

>>> a,b = (1,2)

>>> print a,b

1 2

>>> t = (1,2)

>>> a,b = t

>>> print a,b

1 2

>>> a,b=b,a+1

>>> print a,b

2 2


表示只含有一个元素的tuple的方法是:(1,)后面有个逗号,用来和单独的变量区分。

>>> 3 * (20+1)
63
>>> 3 * (20+1,)
(21, 21, 21)

     tuplelist的性能好,不用提供动态内存管理的功能



tuple 函数

     tuple函数的功能与list函数基本上一样:以一个序列作为参数并把它转换为元组。

>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1,2,3))
(1, 2, 3)


应用:
Multiple Assignment
    my_list = ['Alice', 12, 'Python']
    (name, age, skill) = my_list

Swap
>>> x = 100
>>> y = 99
>>> (x,y) = (y,x)
>>> x
99
>>> y
100

回传多值:
def get_error_details():
        return (2, 'details')

(errnum, errstr) = get_error_details()












将来的你,一定会感谢现在拼命努力的你。
原文地址:https://www.cnblogs.com/51runsky/p/4574577.html