12.1 Tuples are immutable(元组是不可变的)
A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so in that respect tuples are a lot like lists. The important difference is that tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:

>>> t = 'a', 'b', 'c', 'd', 'e'

Although it is not necessary, it is common to enclose tuples in parentheses(通常使用括号括起来):

>>> t = ('a', 'b', 'c', 'd', 'e')

To create a tuple with a single element, you have to include a final comma(创建一个只有1个元素的元组,必须以"逗号"结尾):

>>> t1 = 'a',
>>> type(t1)
<type 'tuple'>

A value in parentheses is not a tuple:

>>> t2 = ('a')
>>> type(t2)
<type 'str'>

Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:

>>> t = tuple()
>>> print t
()

If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence(参数为1个序列,结果为1个元组):

>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')

Because tuple is the name of a built-in function, you should avoid using it as a variable name.
Most list operators also work on tuples(大部分列表的操作在元组中也适用). The bracket operator indexes an element:

>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'

And the slice operator selects a range of elements.

>>> print t[1:3]
('b', 'c')

But if you try to modify one of the elements of the tuple, you get an error:

>>> t[0] = 'A'
TypeError: object doesn't support item assignment

You can’t modify the elements of a tuple, but you can replace one tuple with another(不能改变元组中的元素,不过可以替代一个元组为另外一个):

>>> t = ('A',) + t[1:]
>>> print t
('A', 'b', 'c', 'd', 'e')

12.2 Tuple assignment
It is often useful to swap the values of two variables. With conventional assignments, you have to use a temporary variable. For example, to swap a and b:

>>> temp = a
>>> a = b
>>> b = temp

This solution is cumbersome; tuple assignment is more elegant:

>>> a, b = b, a

The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments.
The number of variables on the left and the number of values on the right have to be the same(左边的变量个数必须和右边的一致):

>>> a, b = 1, 2, 3
ValueError: too many values to unpack

More generally, the right side can be any kind of sequence (string, list or tuple). For example, to split an email address into a user name and a domain, you could write:

>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')

The return value from split is a list with two elements; the first element is assigned to uname, the second to domain.

>>> print uname
monty
>>> print domain
python.org

12.3 Tuples as return values
Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x/y and then x%y. It is better to compute them both at the same time.
The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:

>>> t = divmod(7, 3)
>>> print t
(2, 1)

Or use tuple assignment to store the elements separately:

>>> quot, rem = divmod(7, 3)
>>> print quot
2
>>> print rem
1

Here is an example of a function that returns a tuple:

def min_max(t):
return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a sequence. min_max computes both and returns a tuple of two values.

12.4 Variable-length argument tuples
Functions can take a variable number of arguments. A parameter name that begins with * gathers arguments into a tuple. For example, printall takes any number of arguments and prints them:

def printall(*args):
print args

The gather parameter can have any name you like, but args is conventional. Here’s how the function works:

>>> printall(1, 2.0, '')
(1, 2.0, '')

The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator(可以通过"*"操作符来传递不定参数). For example, divmod takes exactly two arguments; it doesn’t work with a tuple:

>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1

But if you scatter the tuple, it works:

>>> divmod(*t)
(2, 1)
>>> max(1,2,3)
3

But sum does not.

>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3

Write a function called sumall that takes any number of arguments and returns their sum.

12.5 Lists and tuples
zip is a built-in function that takes two or more sequences and “zips” them into a list of tuples where each tuple contains one element from each sequence. In Python 3, zip returns an iterator of tuples, but for most purposes, an iterator behaves like a list.
This example zips a string and a list:

>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]

The result is a list of tuples where each tuple contains a character from the string and the corresponding element from the list.
If the sequences are not the same length, the result has the length of the shorter one(如果两个序列长度不一致,结果长度为短的序列长度).

>>> zip('Anne', 'Elk')
[('A', 'E'), ('n', 'l'), ('n', 'k')]

You can use tuple assignment in a for loop to traverse a list of tuples:

t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print number, letter

Each time through the loop, Python selects the next tuple in the list and assigns the elements to letter and number. The output of this loop is:

0 a
1 b
2 c

If you combine zip, for and tuple assignment, you get a useful idiom for traversing two (or more) sequences at the same time. For example, has_match takes two sequences, t1 and t2, and returns True if there is an index i such that t1[i] == t2[i]:

def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False

If you need to traverse the elements of a sequence and their indices, you can use the built-in function enumerate:

for index, element in enumerate('abc'):
print index, element

The output of this loop is:

0 a
1 b
2 c

Again.

12.6 Dictionaries and tuples
Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair.

>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]

As you should expect from a dictionary, the items are in no particular order. In Python 3, items returns an iterator, but for many purposes, iterators behave like lists.
Going in the other direction, you can use a list of tuples to initialize a new dictionary(通过元组来初始化一个有序的字典):

>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}

Combining dict with zip yields a concise way to create a dictionary:

>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}

The dictionary method update also takes a list of tuples and adds them, as key-value pairs, to an existing dictionary.
Combining items, tuple assignment and for, you get the idiom for traversing the keys and values of a dictionary:

for key, val in d.items():
print val, key

The output of this loop is:

0 a
2 c
1 b

Again.
It is common to use tuples as keys in dictionaries (primarily because you can’t use lists). For example, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:

directory[last,first] = number

The expression in brackets is a tuple. We could use tuple assignment to traverse this dictionary.

for last, first in directory:
print first, last, directory[last,first]

This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number.

There are two ways to represent tuples in a state diagram. The more detailed version shows the indices and elements just as they appear in a list. For example, the tuple ('Cleese', 'John') would appear as in Figure 12.1.
But in a larger diagram you might want to leave out the details. For example, a diagram of the telephone directory might appear as in Figure 12.2.
Here the tuples are shown using Python syntax as a graphical shorthand.
The telephone number in the diagram is the complaints line for the BBC, so please don’t call it.

12.7 Comparing tuples
The relational operators work with tuples and other sequences; Python starts by comparing the first element from each sequence. If they are equal, it goes on to the next elements, and so on, until it finds elements that differ. Subsequent elements are not considered (even if they are really big).

>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True

The sort function works the same way. It sorts primarily by first element, but in the case of a tie, it sorts by second element, and so on.
This feature lends itself to a pattern called DSU for

  • Decorate a sequence by building a list of tuples with one or more sort keys preceding theelements from the sequence,
  • Sort the list of tuples, and
  • Undecorate by extracting the sorted elements of the sequence.

For example, suppose you have a list of words and you want to sort them from longest to shortest:

def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res

The first loop builds a list of tuples, where each tuple is a word preceded by its length.
sort compares the first element, length, first, and only considers the second element to break ties. The keyword argument reverse=True tells sort to go in decreasing order.
The second loop traverses the list of tuples and builds a list of words in descending order
of length.

12.8 Sequences of sequences
I have focused on lists of tuples, but almost all of the examples in this chapter also work with lists of lists, tuples of tuples, and tuples of lists. To avoid enumerating the possible combinations, it is sometimes easier to talk about sequences of sequences.
In many contexts, the different kinds of sequences (strings, lists and tuples) can be used interchangeably. So how and why do you choose one over the others?
To start with the obvious, strings are more limited than other sequences because the elements have to be characters. They are also immutable. If you need the ability to change the characters in a string (as opposed to creating a new string), you might want to use a list of characters instead.
Lists are more common than tuples, mostly because they are mutable. But there are a few cases where you might prefer tuples:

  • In some contexts, like a return statement, it is syntactically simpler to create a tuple than a list. In other contexts, you might prefer a list.
  • If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string.
  • If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing.

Because tuples are immutable, they don’t provide methods like sort and reverse, which modify existing lists. But Python provides the built-in functions sorted and reversed, which take any sequence as a parameter and return a new list with the same elements in a different order.

[全文摘自"Think Python"]

Think Python - Chapter 12 Tuples的更多相关文章

  1. <Web Scraping with Python>:Chapter 1 & 2

    <Web Scraping with Python> Chapter 1 & 2: Your First Web Scraper & Advanced HTML Parsi ...

  2. 十二. Python基础(12)--生成器

    十二. Python基础(12)--生成器 1 ● 可迭代对象(iterable) An object capable of returning its members one at a time. ...

  3. 『Python基础-12』各种推导式(列表推导式、字典推导式、集合推导式)

    # 『Python基础-12』各种推导式(列表推导式.字典推导式.集合推导式) 推导式comprehensions(又称解析式),是Python的一种独有特性.推导式是可以从一个数据序列构建另一个新的 ...

  4. python进阶12 Redis

    python进阶12 Redis 一.概念 #redis是一种nosql(not only sql)数据库,他的数据是保存在内存中,同时redis可以定时把内存数据同步到磁盘,即可以将数据持久化,还提 ...

  5. 零元学Expression Blend 4 - Chapter 12 用实例了解布局容器系列-「Viewbox」

    原文:零元学Expression Blend 4 - Chapter 12 用实例了解布局容器系列-「Viewbox」 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Bl ...

  6. 小白学 Python(12):基础数据结构(字典)(上)

    人生苦短,我选Python 前文传送门 小白学 Python(1):开篇 小白学 Python(2):基础数据类型(上) 小白学 Python(3):基础数据类型(下) 小白学 Python(4):变 ...

  7. python day 12: 选课系统

    目录 python day 12 1. 通过类来创建选课系统 1.1 类库models.py 2. 配置文件setting.py 3. administrator.py 4. student.py p ...

  8. 尚学python课程---12、python语言介绍

    尚学python课程---12.python语言介绍 一.总结 一句话总结: 1.操作简单:简便计算:允许通过单个“import”语句后跟一个函数调用来完成复杂的计算.虽慢 2.库丰富:比如人工智能和 ...

  9. Python 3.12 目标:还可以更快!

    按照发布计划,Python 3.11.0 将于 2022 年 10 月 24 日发布. 据测试,3.11 相比于 3.10,将会有 10-60% 的性能提升,这个成果主要归功于"Faster ...

随机推荐

  1. Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)

    Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...

  2. linux下不能使用shutdown命令

    命令查看:  #echo $PATH     /usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/sbin;/ ...

  3. flash as3 socket安全服务网关(socket policy file server)

    关键字: SecurityErrorEvent socket as3 flash有着自己的一套安全处理模式,在socket方面,我这样的菜鸟无法理解他的好处:一句话,不怀好意的人如果想用flash写一 ...

  4. HDU 4893 Wow! Such Sequence!(2014 Multi-University Training Contest 3)

    题意: 有三种操作: 1 x y: 表示给x位置加上y 2 x y:查询[x,y]的区间和 3 x y:将 [x,y] 区间上的数变为最接近的 Fibonacci. 思路: 1 操作按正常单调更新,区 ...

  5. 周游加拿大(dp好题)

    你赢得了一场航空公司举办的比赛,奖品是一张加拿大环游机票.旅行在这家航空公司开放的最西边的城市开始,然后一直自西向东旅行,直到你到达最东边的城市,再由东向西返回,直到你回到开始的城市.每个城市只能访问 ...

  6. POJ3624

    题目大意: 给出珠宝的重量Wi和珠宝的价值Di,并给定一个重量范围M,在不超过M的情况下求取到的珠宝的最大值,N为列出珠宝的重量. #include <iostream> #include ...

  7. Right-BICEP 测试四则运算二程序

    测试方法: Right-BICEP 测试计划: 1.Right-结果是否正确? 2.B-是否所有的边界条件都是正确的? 3.是否有乘除法? 4.是否有括号? 5.是否有输出方式? 6.是否可以选择出题 ...

  8. VS2010中添加lib库引用

    VS2010中添加lib库引用: 1 菜单  项目---> 属性--->配置属性-->链接器---->输入---附加依赖项,  加入库名,如: my_API.lib; 或是在c ...

  9. new 动态分配数组空间

    (一)定义一个整数              int *p =new int;        int *p =new int(4); //赋初值4 (二)定义一个一维数组                ...

  10. [windows驱动]标准驱动例程

    [注]routine:例行程序. 1.标准驱动例程简介: 每一个内核态驱动程序都是由一系列系统定义的,标准的驱动例程组成.内核态驱动在这些标准例程中通过调用系统提供的驱动支持函数处理I/O请求包.为了 ...