您的位置:首页 > 编程语言 > Python开发

Think Python: Chapter 12 Tuples

2015-04-22 22:57 309 查看

目录

这是麻省理工大学(MIT)官方编程教程中Python Tutorial的内容,教材为《Think Python: How to Think Like a Computer Scientist》。这是我的学习笔记,因为水品有限,请大家多多包涵。如果有一起学习的同学可以一起交流。如笔记中错误,请一定要告诉我啊,我肯定及时改正。所有笔记的目录详见:MIT:Python Tutorial目录

这是MIT官方编程教程中Python TutorialLoops and List Comprehensions的内容。本篇博客为《 Think Python: How to Think Like a Computer Scientist》(Think Python, Chapter 12 Tuples

Python Tutorial:Loops and List Comprehensions

Chapter 12 Tuples(数组)

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.(元组和list差不多,values可以是任何类型,index必须是整数.但是比较重要的区别是tuples是不可变的)

tuple: An immutable sequence of elements.

A tuple is a comma-separated list of values:

#tuple赋值1
>>> t=('a','b','c','d','e')

#tuple赋值方式的不同
>>> t1='a'
>>> type(t1)
<class 'str'>
#tuple的赋值,注意逗号
>>> t2=('a',)
>>> type(t2)
<class 'tuple'>

#tuple的特点是括号()
>>> t=tuple()
>>> print (t)
()

#tuple与list相似的一些用法
>>> t=tuple('lupins')
>>> print(t)
('l', 'u', 'p', 'i', 'n', 's')
>>> print(t[0])
l
>>> print(t[1:3])
('u', 'p')

#tuple里的值不可改变
>>> t[0]='a'
TypeError: 'tuple' object does not support item assignment

#要修改tuple里的值,必须要整个地附一个新值
#注意('a',)中的逗号
>>> t=('a',)+t[1:]
>>> print(t)
('a', 'u', 'p', 'i', 'n', 's')


12.2 Tuple assignment

tuple assignment: An assignment with a sequence on the right side and a tuple of variables on the left. The right side is evaluated and then its elements are assigned to the variables on the left.

交换值,不需要用中间变量转换了

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


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.

(tuple可以返回多个值,感受一下)

#divmod()是自带函数,先输出div,在输出mod
>>> t=divmod(7,3)
>>> print(t)
(2, 1)

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


可以返回两个值的函数设计,当然也可以返回多个值:

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


12.4 Variable-length argument tuples

*gathers arguments: The operation of assembling(汇编) a variable-length argument tuple.(gather最大的作用是可以按顺序一个一个地取出一系列的值)

scatter: The complement of gather is scatter. The operation of treating(处理) a sequence as a list of arguments.

(gather的特征是参数前有一个*)

>>> t=(7,3)
>>> divmod(t)#divmod无法处理tuple类型的参数,所以会报错
TypeError: divmod expected 2 arguments, got 1

#看看使用gather的方式,用*将tuple中的值依次取出,让divmod可处理
>>> divmod(*t)
(2, 1)


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.

(zip产生一系列tuples构成的list)

>>> s='abc'
>>> t=[0,1,2]
>>> list1=zip(s,t)

#逐个输出
>>> for a,b in list1:
print(a,b)

a 0
b 1
c 2
>>>


zip的功能可以实现匹配功能,比如:

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


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.(dictionary可以用items返回一系列的tuples)

#用items返回tuples,形成lists
>>> d={'a':0,'b':1,'c':2}
>>> t=d.items()
>>> print(t)
dict_items([('a', 0), ('b', 1), ('c', 2)])

#将tuples封装到dict中去
>>> d2=dict(t)
>>> print (d2)
{'a': 0, 'b': 1, 'c': 2}

#加上zip形成tuples,再将其封装到dict中去
>>> d3=dict(zip('abc',range(3)))
>>>
>>> print(d3)
{'a': 0, 'b': 1, 'c': 2}

#让dict以tuple的方式输出
>>> for key,val in d.items():
print(val,key)

0 a
1 b
2 c


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)

(tuples之间的比较是按顺序一个一个比较的,谁先大,谁就大,和string的比较差不多)

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

#后面的级别再大也没用
>>> (0,1,20000000)<(0,3,4)
True


大小的排序:DSU

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 the elements 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=[]#t是list
for word in words:
t.append(len(word),word)
#t中的values是tuples,一组包括长度和word

t.sort(reverse=True)
#将t排序,排序依据是第一个element(length)从大到小排序,再将word的从大到小排序

res=[]#res也是list
for length,word in t:
res.append(word)#根据长度排序从大到小,依次取word
return res


12.8 Sequences of sequences(怎么选择string,list,tuple)

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.

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.

(string有诸多的限制,比如说成员必须是characters,同时还是不可变的.如果要使用可变的characters的系列,你应该选择list of characters)

Lists are more common than tuples, mostly because they are mutable.(list比tuple常见,是因为list可以改变.)

But there are a few cases where you might prefer tuples:(但以下几个情况,你可能更加需要tuples)

1. 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.(在return语句中,使用tuple会比list更加方便)

2. If you want to use a sequence as a dictionary key, you have to use an immutable type like a tuple or string.(用于字典的keys,使用不可变的string和tuples可能会更加值得考虑)

3. If you are passing a sequence as an argument to a function, using tuples reduces the potential for unexpected behavior due to aliasing.(在作为函数的参数的时候,tuples会更加可靠)

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.

(因为tuples的不可变,所以它无法使用lists的一些methods,比如sort和reverse.但是python有sorted和reversed函数用于处理所有sequence型的数据,并输出排序好后的新lists)

12.9 Debugging(这里提供超级有用的函数)

Lists, dictionaries and tuples are known generically as data structures; in this chapter we are starting to see compound(合成的) data structures, like lists of tuples, and dictionaries that contain tuples as keys and lists as values. Compound data structures are useful, but they are prone to what I call shape errors; that is, errors caused when a data structure has the wrong type, size or composition. For example, if you are expecting a list with one integer and I give you a plain(简单的) old integer (not in a list), it won’t work.

To help debug these kinds of errors, I have written a module called structshape that provides a function, also called structshape, that takes any kind of data structure as an argument and returns a string that summarizes its shape. You can download it from http://thinkpython.com/code/structshape.py

(超级棒的函数,别忘了去这个网站下载下来.可以用来判断你的data structure中有几个什么类型的数据)

data structure: A collection of related values, often organized in lists, dictionaries, tuples, etc.

shape (of a data structure): A summary of the type, size and composition of a data structure.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 教程