31.html ( File view )
- By 2010-08-21
- View(s):12
- Download(s):0
- Point(s): 1
Safari | Python Developer's Handbook -> Data Structures
See All Titles |
![]() ![]() Data StructuresPython implements a variety of data structures, such as lists, tuples, ranges, and dictionaries (also known as hash tables). ListsLists are mutable sequences of objects indexed by natural numbers that can be changed after they are created. Lists are very flexible and easy to create. They are always enclosed in brackets: >>> lst = [1,2,3,4] # this is simple list A list can have elements of different data types: >>> lst = [1, "ni!", 2] Lists can also include other lists: >>> lst = [1, "ni!", [1,2,"Albatross!!"]] A list uses the same operators that strings use. For example, you need to use slice notation to grab a range of elements from a list. >>> lst = [1, "ni!", [1, 2, 3, 4, "Albatross!!", 3]] >>> lst[1] "ni!" To grab elements from lists that are located inside other lists, you need to use a pair of brackets to represent each list. Check out the next couple of examples. >>> lst = [1, "ni!", [1, 2, 3, 4, "Albatross!!", 3]] >>> lst[2][4] "Albatross!!" >>> lst[2][4][5] "r" Let's see some examples of operations that can be applied to a list. Identifying an Entry>>> lst = ["p", "a", "r", "r", "o", "t"] >>> lst.index("o") 4 Assigning Values to a List>>> lst = ["p", "a", "r", "r", "o", "t"] >>> lst[1] = "aaaaaaaaaaaaa" >>> lst ["p", "aaaaaaaaaaaaa", "r", "r", "o", "t"] Assigning Values to a Slice>>> lst = ["p", "a", "r", "r", "o", "t"] >>> lst[1:4] = ["aaaaaaaaaaaaa", "rrr", "rrrr"] >>> lst ["p", "aaaaaaaaaaaaa", "rrr", "rrrr", "o", "t"] Inserting ValuesThe following example starts inserting values at index number 6. >>> lst = ["p", "a", "r", "r", "o", "t"] >>> lst[6:] = [" ", "s", "k", "e", "t", "c", "h"] ['p', 'a', 'r', 'r', 'o', 't', '', 's', 'k', 'e', 't', 'c', 'h'] If the list was longer than 6 elements, the statement would overwrite a portion of the list. Note that you can also insert a value in this list with >>> lst.insert(6, val) Deleting a Value>>> lst = ["p", "a", "r", "r", "o", "t"] >>> del lst[-1] >>> lst ["p", "a", "r", "r", "o"] >>> del lst[0:2] ["r", "r", "o"] The following example converts objects to their string representation: >>> lst = [10,20,30,"inquisition","lumberjack"] >>> text = "" >>> for element in lst: text = text + `element` # enables the concatenation of any object print text 10 1020 102030 102030'inquisition' 102030'inquisition''lumberjack' List ComprehensionStarting with release 2.0, there is a new notation to create lists whose elements are computed from another list (or lists). The method is called List Comprehension, and it adopts the following format: [ expression for expression1 in sequence1 [for expression2 in sequence2] [ for expressionN in sequenceN] [if condition] ] All forin clauses are evaluated and iterated from left to right. That means that the resulting list is a cartesian product of the given sequences. For example, if you have three lists of length 5, the output list has 125 elements. The if clause is optional, but when present, it can limit the number of pairs that will become part of the resulting list by adding pairs to the resulting list only when the result condition of the if statement evaluates to true. Check the following example: letters = 'py' numbers = (1.52, 1.6, 2.0) >>> [ (l,n) for l in letters for n in numbers] [('p', 1.52), ('p', 1.6), ('p', 2.0), ('y', 1.52), ('y', 1.6), ('y', 2.0)] This new concept is more efficient than a for loop with an if statement along with a list.append() function call. Built-In MethodsTo list all the built-in methods of a list, go to the interpreter and type dir([]). Let's practice the methods that you have found, and see what happens to our list lst. >>> lst = [0, 1, 2] >>> lst.append(5) # appends the element 5 to the list >>> lst [0, 1, 2, 5] >>> lst.append((5, 6)) # appends the tuple (5, 6) >>> lst [0, 1, 2, 5, (5, 6)] >>> lst.pop() # removes the last element of the list (5, 6) >>> lst [0, 1, 2, 5] >>> lst.insert(2,7) # inserts the element 7 at index number 2 >>> lst [0, 1, 7, 2, 5] >>> lst.pop(2) # removes the element at index number 2 7 >>> lst [0, 1, 2, 5] >>> lst.reverse() # reverse the list order >>> lst [5, 2, 1, 0] >>> lst.sort() # sorts the list elements >>> lst [0, 1, 2, 5] >>> lst.extend([3, 4, 5]) # adds this list to our original list >>> lst [0, 1, 2, 5, 3, 4, 5] >>> lst.count(5) # counts the number of elements number 5 that exist. 2 >>> lst.index(3) # returns the associated index of element 3. 4 >>> lst.remove(2) # removes the element number 2 (not the index!!!) >>> lst [0, 1, 5, 3, 4, 5] Note that up to release 1.5.2, whenever you used lst.append (1,2), a tuple (1,2) would be appended to the list lst. Now, with release 2.0, when you do that, you get an TypeError exception followed by a message like " append requires exactly 1 argument; 2 given ". Don't panic! To fix that, you just need to add an extra pair of parenthesis, like this: lst.append ((1,2)). RangesA range is an actual list of integers. The built-in function range() provides this data structure. >>> r = range(2,5) >>> print r [2,3,4]... ... (Not finished, please download and read the complete file) ...
Expand> <Close
Sponsored links
File listTips: You can preview the content of files by clicking file names^_^
|
Your Point isn't enough.
Get point immediately by PayPal
More(Debit card / Credit card / PayPal Credit / Online Banking)