python-lectures-4_第1页
python-lectures-4_第2页
python-lectures-4_第3页
python-lectures-4_第4页
python-lectures-4_第5页
已阅读5页,还剩20页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Python Crash CourseContainers,Bachelors V1.0 dd 13-01-2015 Hour 6,Introduction to language - containers,Container data types in Python are types whose instances are capable of storing other objects. Some of the fundamental built-in container objects include: lists the most popular container data typ

2、e in python; can store any number of any objects. tuples similar to list, yet once created are immutable, sets can store only unique elements, bytes immutable sequence of integers in the range 0 = x 256, bytearray like bytes, but mutable, dictionary also known as associative arrays. They contain map

3、ping of keys into value, str string, a sequence of unicode characters, range a sequence of numbers more precisely a list containing arithmetic progressions array.array present in the array module. Similar to list, yet during the construction it is restricted to holding a specific data type,Container

4、s Mutable, Immutable, Hashable,Containers in Python can be either mutable or immutable. The fact that a container object is immutable doesnt always mean that the objects it holds are also immutable (e.g. an immutable tuple holding mutable lists). However, container objects are fully immutable only i

5、f the object itself, and the objects it contains are recursively immutable. Recursively immutable objects may be hashable. This is important as only hashable objects can be used in a mapping container object (see below) as keys. Mutable Definition: Mutable objects can change their value but keep the

6、ir id(). Immutable Definition: An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for

7、 example as a key in a dictionary. Hashable Definition: An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash()method), and can be compared to other objects (it needs an eq() method). Hashable objects which compare equal must have the same hash value.,

8、Containers Mutable, Immutable, Hashable,All of Pythons immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Examples of mutable containers include: list, set, dictionary, bytearray array Examples of immutable containers include: numbers string, fr

9、ozenset, tuple, bytes The main implication of the mutable/immutable distinction and hashability is that not all container objects can store all other container objects, in particular: sets can store only hashable object (each object in set has to have a unique hash sets do not store duplicate object

10、s, as opposed to e.g. lists or tuples) dictionaries can have only hashable objects as keys,Containers Ordered or Unordered,Container object can store their content in either an ordered or unordered manner. Order, or lack of thereof, is unrelated to the mutability of objects. This means that both mut

11、able and immutable objects can be either ordered or unordered. Examples of ordered containers include: list, string, tuple, bytes, bytearrays, array Examples of unordered containers include: dictionary, set, frozenset.,Introduction to language - containers,Containers - Lists,Lists: a = 1, 2, 4, 8, 1

12、6 # list of ints c = 4, candles, 4.0, handles # can mix types c1 candles c2 = knife c-1 # negative indices count from end handles c1:3 # slicing candles, knife c2: # omitting defaults to start or end knife, handles c0:4:2 # variable stride (could just write c:2) 4, knife a + c # concatenate 1, 2, 4,

13、 8, 16, 4, candles, knife, handles len(a) 5,Lists are the most versatile of Pythons compound data types. A list contains items separated by commas and enclosed within square brackets (). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to

14、a list can be of different data type. The values stored in a list can be accessed using the slice operator ( and : ) with indexes starting at 0 in the beginning of the list and working their way to end-1. The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetitio

15、n operator.,Lists Methods,List operations,list1 = physics, chemistry, 1997, 2000 print list1 del list12 print After deleting value at index 2 : print list1 L = #empty list L = list() A = B = # both names will point to the same list A = B = A # both names will point to the same list A = ; B = # indep

16、endent lists,for item in L: print item for index, item in enumerate(L): print index, item i = iter(L) item = i.next() # fetch first value item = i.next() # fetch second value stack = stack.append(object) # push object = stack.pop() # pop from end queue = queue.append(object) # push object = queue.po

17、p(0) # pop from beginning,List Comprehension, squares = for x in range(10): . squares.append(x*2) . squares 0, 1, 4, 9, 16, 25, 36, 49, 64, 81,List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations appl

18、ied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.,squares = x*2 for x in range(10), matrix = . 1, 2, 3, 4, . 5, 6, 7, 8, . 9, 10, 11, 12, . ,To transpose this matrix: rowi for row in matrix for i in range(4) 1, 5, 9, 2,

19、 6, 10, 3, 7, 11, 4, 8, 12,Nested list comprehension,Containers - Tuples,Tuples: q = (1, 2, 4, 8, 16) # tuple of ints r = (4, candles, 4.0, handles) # can mix types s = (lonely,) # singleton t = () # empty r1 candles r2 = knife # cannot change tuples Traceback (most recent call last): File , line 1,

20、 in TypeError: tuple object does not support item assignment u = 3, 2, 1 # parentheses not necessary v, w = this, that v this w that,A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclos

21、ed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( ), and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of asread-onlylists., u = 3, 2,1 print u (3, 2, 1) v

22、= 4,6,7 w=v+u print w (4, 6, 7, 3, 2, 1) ,Use of tuples,def func(x,y): # code to compute x and y return (x,y) (x,y) = func(1,2),Tuple methods,Note: Tuples have no append or extend methods, nor can you remove items as there are no remove or pop methods either.,Containers - Sets,A set is an unordered

23、collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference., basket = apple, orange, apple, pear, orange, banana fruit = set(basket) #

24、create a set without duplicates fruit set(orange, pear, apple, banana) orange in fruit # fast membership testing True crabgrass in fruit False, x = set(A Python Tutorial) x set(A, , i, h, l, o, n, P, r, u, t, a, y, T) type(x) ,Containers - Sets,No mutable objects, cities = set(Python,Perl, Paris, Ber

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论