首页 Python Data Structures-list

Python Data Structures-list

举报
开通vip

Python Data Structures-list3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html1/135. Data StructuresThis chapter describes some things you’ve lear...

Python Data Structures-list
3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html1/135. Data StructuresThis chapter describes some things you’ve learned about already in more detail, andadds some new things as well.5.1. More on ListsThe list data type has some more methods. Here are all of the methods of list objects:list.append(x)Add an item to the end of the list. Equivalent to a[len(a):] = [x].list.extend(L)Extend the list by appending all the items in the given list. Equivalent toa[len(a):] = L.list.insert(i, x)Insert an item at a given position. The first argument is the index of the elementbefore which to insert, so a.insert(0, x) inserts at the front of the list, anda.insert(len(a), x) is equivalent to a.append(x).list.remove(x)Remove the first item from the list whose value is x. It is an error if there is no suchitem.list.pop([i])Remove the item at the given position in the list, and return it. If no index isspecified, a.pop() removes and returns the last item in the list. (The squarebrackets around the i in the method signature denote that the parameter is optional,not that you should type square brackets at that position. You will see this notationfrequently in the Python Library Reference.)list.clear()Remove all items from the list. Equivalent to del a[:].list.index(x)Return the index in the list of the first item whose value is x. It is an error if there isno such item.list.count(x)Return the number of times x appears in the list.list.sort(key=None, reverse=False)3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html2/13Sort the items of the list in place (the arguments can be used for sort customization,see sorted() for their explanation).list.reverse()Reverse the elements of the list in place.list.copy()Return a shallow copy of the list. Equivalent to a[:].An example that uses most of the list methods:You might have noticed that methods like insert, remove or sort that only modify thelist have no return value printed – they return the default None. [1] This is a designprinciple for all mutable data structures in Python.5.1.1. Using Lists as StacksThe list methods make it very easy to use a list as a stack, where the last elementadded is the first element retrieved (“last­in, first­out”). To add an item to the top of thestack, use append(). To retrieve an item from the top of the stack, use pop() withoutan explicit index. For example:>>> a = [66.25, 333, 333, 1, 1234.5] >>> print(a.count(333), a.count(66.25), a.count('x')) 2 1 0 >>> a.insert(2, ‐1) >>> a.append(333) >>> a [66.25, 333, ‐1, 333, 1, 1234.5, 333] >>> a.index(333) 1 >>> a.remove(333) >>> a [66.25, ‐1, 333, 1, 1234.5, 333] >>> a.reverse() >>> a [333, 1234.5, 1, 333, ‐1, 66.25] >>> a.sort() >>> a [‐1, 1, 66.25, 333, 333, 1234.5] >>> a.pop() 1234.5 >>> a [‐1, 1, 66.25, 333, 333] >>>>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack >>>3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html3/135.1.2. Using Lists as QueuesIt is also possible to use a list as a queue, where the first element added is the firstelement retrieved (“first­in, first­out”); however, lists are not efficient for this purpose.While appends and pops from the end of list are fast, doing inserts or pops from thebeginning of a list is slow (because all of the other elements have to be shifted by one).To implement a queue, use collections.deque which was designed to have fastappends and pops from both ends. For example:5.1.3. List ComprehensionsList comprehensions provide a concise way to create lists. Common applications are tomake new lists where each element is the result of some operations applied to eachmember of another sequence or iterable, or to create a subsequence of those elementsthat satisfy a certain condition.For example, assume we want to create a list of squares, like:[3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4] >>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry")           # Terry arrives >>> queue.append("Graham")          # Graham arrives >>> queue.popleft()                 # The first to arrive now leaves 'Eric' >>> queue.popleft()                 # The second to arrive now leaves 'John' >>> queue                           # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham']) >>>>>> squares = [] >>> for x in range(10): ...     squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>>3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html4/13Note that this creates (or overwrites) a variable named x that still exists after the loopcompletes. We can calculate the list of squares without any side effects using:or, equivalently:which is more concise and readable.A list comprehension consists of brackets containing an expression followed by a forclause, then zero or more for or if clauses. The result will be a new list resulting fromevaluating the expression in the context of the for and if clauses which follow it. Forexample, this listcomp combines the elements of two lists if they are not equal:and it’s equivalent to:Note how the order of the for and if statements is the same in both these snippets.If the expression is a tuple (e.g. the (x, y) in the previous example), it must beparenthesized.squares = list(map(lambda x: x**2, range(10))) squares = [x**2 for x in range(10)]>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] >>>>>> combs = [] >>> for x in [1,2,3]: ...     for y in [3,1,4]: ...         if x != y: ...             combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] >>>>>> vec = [‐4, ‐2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [‐8, ‐4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4] >>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4] >>> # call a method on each element >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] >>>3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html5/13List comprehensions can contain complex expressions and nested functions:5.1.4. Nested List ComprehensionsThe initial expression in a list comprehension can be any arbitrary expression, includinganother list comprehension.Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length4:The following list comprehension will transpose rows and columns:As we saw in the previous section, the nested listcomp is evaluated in the context of thefor that follows it, so this example is equivalent to:>>> # create a list of 2‐tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)]   File "<stdin>", line 1, in ?     [x, x**2 for x in range(6)]                ^ SyntaxError: invalid syntax >>> # flatten a list using a listcomp with two 'for' >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']>>>>>> matrix = [ ...     [1, 2, 3, 4], ...     [5, 6, 7, 8], ...     [9, 10, 11, 12], ... ] >>>>>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] >>>>>> transposed = [] >>> for i in range(4): ...     transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] >>>3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html6/13which, in turn, is the same as:In the real world, you should prefer built­in functions to complex flow statements. Thezip() function would do a great job for this use case:See Unpacking Argument Lists for details on the asterisk in this line.5.2. The del statementThere is a way to remove an item from a list given its index instead of its value: the delstatement. This differs from the pop() method which returns a value. The delstatement can also be used to remove slices from a list or clear the entire list (which wedid earlier by assignment of an empty list to the slice). For example:del can also be used to delete entire variables:Referencing the name a hereafter is an error (at least until another value is assigned toit). We’ll find other uses for del later.5.3. Tuples and Sequences>>> transposed = [] >>> for i in range(4): ...     # the following 3 lines implement the nested listcomp ...     transposed_row = [] ...     for row in matrix: ...         transposed_row.append(row[i]) ...     transposed.append(transposed_row)... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] >>>>>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] >>>>>> a = [‐1, 1, 66.25, 333, 333, 1234.5] >>> del a[0] >>> a [1, 66.25, 333, 333, 1234.5] >>> del a[2:4] >>> a [1, 66.25, 1234.5] >>> del a[:] >>> a [] >>>>>> del a >>>3/15/20165. Data Structures — Python 3.5.1 documentationhttps://docs.python.org/3/tutorial/datastructures.html7/13We saw that lists and strings have many common properties, such as indexing andslicing operations. They are two examples of sequence data types (see SequenceTypes — list, tuple, range). Since Python is an evolving language, other sequence datatypes may be added. There is also another standard sequence data type: the tuple.A tuple consists of a number of values separated by commas, for instance:As you see, on output tuples are always enclosed in 
本文档为【Python Data Structures-list】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_903254
暂无简介~
格式:pdf
大小:323KB
软件:PDF阅读器
页数:0
分类:互联网
上传时间:2017-10-09
浏览量:17