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

Think Python: Chapter 10 Lists

2015-04-22 22:52 330 查看

目录

这是麻省理工大学(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 10 Lists

Chapter 10 Lists

10.1 A list is a sequence

list: A sequence of values.(一系列值)

element: One of the values in a list (or other sequence), also called items.(数组的成员)

index: An integer value that indicates an element in a list.(表示某一成员在数组中的位置)

nested list: A list that is an element of another list.

mapping: A relationship in which each element of one set corresponds(一致,对应) to an element of another set. For example, a list is a mapping from indices to elements.

10.2 Lists are mutable(数组是可变的)

#数组list的使用方式和字符串string是一样的,但是list中的element是可变的.
>>> cheeses=['Cheddar','Edam','Gouda']
>>> 'Edam' in cheeses
True

#与string比较大的区别,是list定义的数组里面的成员element是可变的.
>>> cheeses[2]='Bird'
>>> print(cheeses)
['Cheddar', 'Edam', 'Bird']


10.3 Traversing a list(数组的遍历)

list traversal(数组的遍历): The sequential accessing of each element in a list.(方式和string是一样的)

>>> for cheese in cheeses:
print(cheese)

#输出效果
Cheddar
Edam
Bird


10.4 List operations(数组运算)

The + operator concatenates lists:(加法运算链接数组)

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=a+b
>>> print(c)
[1, 2, 3, 4, 5, 6]


the * operator repeats a list a given number of times:(乘法运算重复数组次数)

>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]


10.5 List slices(提取数组片段)

与string相同

10.6 List methods(数组的一些运算)

append: adds a new element to the end of a list(append在数组的最后添加一个新的element):

>>> a=[1,2,3]
>>> a.append(4)
>>> print (a)
[1, 2, 3, 4]


extend: takes a list as an argument and appends all of the elements(extend将一个数组全部加到另一个数组的后面):

>>> t1=['a','b','c']
>>> t2=['d','e']
>>> t1.extend(t2)#将t2拓展到t1中
>>> print(t1)
['a', 'b', 'c', 'd', 'e']


sort arranges the elements of the list from low to high(sort用于从低到高的排序):

>>> t=['d','c','a','b','f']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'f']


[注意]List methods are all void; they modify the list and return None. If you accidentally write t=t.sort()[这个写法是错误的,因为list的methods都没有返回值,所以不能用=赋值] , you will be disappointed with the result.

10.7 Map(遍历), filter(过滤) and reduce(减少)

map: A processing pattern that traverses a sequence and performs an operation on each element.(map即是数组的遍历程序)

To add up all the numbers in a list, you can use a loop like this(数组内叠加):

#10.7 1 add_all
def add_all(t):
total=0
for x in t:
total+=x
return total


total+=x相当于total=total+x,这叫做augmented(增大) assignment

augmented assignment: A statement that updates the value of a variable using an operator like +=.

total这个变量,在这里可以称作是accumulator(累加者)

accumulator(累加者): A variable used in a loop to add up or accumulate a result.

累加这个功能也可以有built-in函数 sum() 来完成:

>>> sum(c)
21


这种将一个数组转换成一个值的方式有时候可以称作 reduce

reduce: A processing pattern that traverses a sequence and accumulates the elements into a single result.

Sometimes you want to traverse one list while building another. For example, the following function takes a list of strings and returns a new list that contains capitalized strings(有的时候你可能需要遍历整个数组,虽然你有比较更好的method,比如说如果我们需要将数组里的所有字符都大写的话):

#10.7-2 遍历数组大写
def capitalize_all(t):
res=[]
for s in t:
res.append(s.upper())
return res

#测试结果
>>> t=['d','c','a','b','f']
>>> capitalize_all(t)
['D', 'C', 'A', 'B', 'F']


Another common operation is to select some of the elements from a list and return a sublist.For example, the following function takes a list of strings and returns a list that contains only the uppercase strings:(另一个比较常用的方法是从数组中挑选出符合条件的element组成一个新的数组,例如从数组中选出大写的letter)

#10.7-3 选择符合条件的数据并组成新的数组
def only_upper(t):
res=[]
for s in t:
if s.isupper():#isupper是内置的判断是否大写的函数
res.append(s)#在 res的结尾添加大写的elements.
#在此注意,append是没有返回值的,所以不能写成res=res.appen(s)
return res

#测试结果
>>> t=['D','c','A','b','f']
>>> only_upper(t)
['D', 'A']


only_upper 这种方式可以称作是filter(过滤器)

filter: A processing pattern that traverses a list and selects the elements that satisfy some criterion.

Most common list operations can be expressed as a combination of map, filter and reduce. Because these operations are so common, Python provides language features to support them, including the built-in function map and an operator called a “list comprehension .”

(大多数数组的运算都是通过map,filter和reduce表达的,所有这些运算都可以称作为”list comprehension”)

10.8 Deleting(删除) elements

There are several ways to delete elements from a list. If you know the index of the element you want, you can use pop ,pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element. :(用pop()删除数组中某一特定index的值,如果没有设定,则删除数组最后面的那个element.pop()在删除某个值的过程中,会返回被删除的那个值)

>>> t=['D','c','A','b','f']
>>> a=t.pop(3)
>>> print(t)
['D', 'c', 'A', 'f']
>>> print(a)
b


del(根据index删除) :If you don’t need the removed value, you can use the del operator:(如果不需要返回值,可以使用del.del根据index删除)

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

#删除多个
>>> t=['a','b','c','d','e']
>>> del t[1:3]
>>> print(t)
['a', 'd', 'e']


remove(根据内容删除) :If you know the element you want to remove (but not the index), you can use remove:

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


10.9 Lists and strings(一些处理string的methods,特别是string和list的相互转换)

A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list :(用list将string变成character的list)

>>> s='spam'
>>> t=list(s)
>>> print(t)
['s', 'p', 'a', 'm']


The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:(用split将string转变成多个word)

>>> s='pining for the think python'
>>> t=s.split()
>>> print(t)
['pining', 'for', 'the', 'think', 'python']


An optional argument called a delimiter specifies which characters to use as word boundaries(边界). The following example uses a hyphen(连号) as a delimiter:(用delimiter的方法确定word的边界)

>>> s='spam-spam-spam-span-spa'
>>> delimiter='-'
>>> s.split(delimiter)
['spam', 'spam', 'spam', 'span', 'spa']


join is the inverse(相反的) of split . It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:(join的用处与split相反,是在数组成员中间加入某些成分)

>>> t=['spam', 'spam', 'spam', 'span', 'spa']
>>> delimiter=' '
>>> delimiter.join(t)
'spam spam spam span spa'


10.10 Objects and values

In one case, a and b refer to two different objects that have the same value. In the second case, they refer to the same object.

To check whether two variables refer to the same object, you can use the is operator.

(两个值一样的对象有两种可能的对应关系,一种是指向同一个位置,一种是虽然值一样,但是值储存的位置不同,为了检验是否是哪种情况,我们可以用 is 这个运算去验证)

第一种情况,string.In this example, Python only created one string object, and both a and b refer to it.(赋值相同的string的对象指的地址是一个地址,所以a就是b)

>>> a='banana'
>>> b='banana'
>>> a is b
True


But when you create two lists , you get two objects:(使用数组的方式,虽然值是相同的,但是指向的位置不同,因此a,b不是同个概念.这也是为什么string不可更改,list可以更改的原因之一)

>>> a=[1,2,3]
>>> b=[1,2,3]
>>> a is b
False


object: Something a variable can refer to. An object has a type and a value.

equivalent(相等): Having the same value.

identical(相同): Being the same object (which implies equivalence).

10.11 Aliasing(别名,化名)

If a refers to an object and you assign b = a, then both variables refer to the same object:(若想数组的a与b identical,可用=)

>>> a=[1,2,3]
>>> b=a

>>> a is b
True


reference: The association between a variable and its value.

aliasing: A circumstance where two or more variables refer to the same object.

10.13 Debugging

Don’t forget that most list methods modify the argument and return None. This is the opposite of the string methods, which return a new string and leave the original alone.(注意大多数的list methods没有返回值,而string是会返回一个新的string,并保留原来的string)

Pick an idiom(习语) and stick(坚持) with it.(坚持使用相同的习语)

Make copies to avoid aliasing.**(为防止aliasing问题,最好留一个数据的备份)**If you want to use a method like sort that modifies the argument, but you need to keep the original list as well, you can make a copy.

10.15 Exercises

Exercise 10.6.

#Exercise 10.6.判断是否已排序
def is_sorted(t):
t2=[]
for x in t:
t2.append(x)
t.sort()
if t2==t:
return True
else:
return False


Exercise 10.7. anagrams(回文构词)

#Exercise 10.7. 判断两个words是否为anagrams(回文构词)
def is_anagram(w1,w2):
if len(w1)!=len(w2):
return False
w11=w1[::-1]#倒着取值
if w11==w2:
return True
return False


哎,别的exercise以后再做吧

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 教程