python data structure

The most basic and important part of learning a language is data structure, which in python is sequence or array, but seems to be more powerful than arrays.

>>> jason=['jason',42] >>> james=['james',45] >>> database=[jason,james] >>> database [['jason', 42], ['james', 45]] >>>

Index:

>>> greeting='hello' >>> greeting[0] 'h' >>> greeting[-1] ==>On the contrary, from-1 Instead of starting with 0 'o' >>> digital=raw_input ("year:")[3] year:2013 >>> digital '3'

Example index:

>>> months=['January','February','March','April',\ 'May','June','July','August','September','October'\ 'November','December'] #Print the date digitally based on the specified year, month, day >>> endings=['st','nd','rd']+17*['th']+['st','nd','rd']+7*['th']+['st'] #List ending with numbers 1-31 >>> year=raw_input ("Year:") Year:2013 >>> month=raw_input('Month(1-12):') Month(1-12):3 >>> day=raw_input('Day(1-31):') Day(1-31):30 >>> month_num=int(month) >>> day_num=int(day) >>> month_name=months[month_num-1] ==>Note that the index is reduced by 1 here >>> ordinal=day+endings[day_num-1] >>> print month_name +' '+ordinal + ', '+ year March 30th, 2013 >>>

Sections:

Indexes provide access to a single element, slices provide access to a range of elements, and slices are implemented by two indices separated by colons.

>>> tag='<a href="http://www.python.org">Python web site</a>' >>> tag[9:30] 'http://www.python.org' >>> tag[32:-4] 'Python web site'>>>

>>> numbers=[1,2,3,4,5,6,7,8,9,10] >>> numbers[3:6] [4, 5, 6] >>> numbers[-3:-1] [8, 9] >>> numbers[-3:0] #The leftmost index in a slice appears later in the sequence than the index to its right, resulting in an empty sequence [] >>> numbers[-3:] #Default to Last [8, 9, 10] >>> numbers[:3] #Start first by default [1, 2, 3] >>> numbers[:] #Default All [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

It is clear that the implementation of a fragmentation operation requires two indexes as boundaries, the elements of the first index being contained in the fragment and the elements of the second not.

Split step: default step is not written, 1, slice format: upper boundary: lower boundary: step

>>> numbers[0:10:1] #Default step size is 1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers[0:10:2] #Set step size to 2 [1, 3, 5, 7, 9] >>> numbers[3:6:3] #Step size set to 3 [4] >>> numbers[::4] [1, 5, 9] >>> numbers[8:3:-1] #Step cannot be zero because it will not execute down, it can be negative and execute forward [9, 8, 7, 6, 5] >>> numbers[10:0:-2] #When the step size is negative, the start index must be greater than the end index [10, 8, 6, 4, 2] >>> numbers[0:10:-2] [] >>> numbers[::-2] [10, 8, 6, 4, 2] >>> numbers [5::-2] [6, 4, 2] >>> numbers[:5:-2] [10, 8] >>>

Sequence addition:

>>> [1,2,3]+[4,5,6] [1, 2, 3, 4, 5, 6] >>> [1,2,3]+'world' #Lists and strings are sequences, but they cannot be joined together so that two sequences of the same type can be joined Traceback (most recent call last): File "<pyshell#141>", line 1, in <module> [1,2,3]+'world' TypeError: can only concatenate list (not "str") to list >>>

Multiplication of sequences:

>>> 'python'*5 'pythonpythonpythonpythonpython' >>> [25]*10 [25, 25, 25, 25, 25, 25, 25, 25, 25, 25]

An empty list can be simply represented by [], but if you want to create a list that takes up ten elements, it doesn't include any useful content lists.You need to use None, which is Python's built-in value, to initialize a 10-length list as follows:

>>> sequence=[None]*10 >>> sequence [None, None, None, None, None, None, None, None, None, None]

Example of sequence multiplication: (run in script exists)

sentence=raw_input ("Sentence:") screen_width=60 text_width=len(sentence) box_width=text_width+6 left_margin=(screen_width-box_width)//2 print print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' print ' ' * left_margin + '| ' + ' ' * text_width +' |' print ' ' * left_margin + '| ' + sentence +' |' print ' ' * left_margin + '| ' + ' ' * text_width +' |' print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' print raw_input()

The results are as follows:

In operator: checks if a value is in a sequence

>>> permission='rwx' #You think it's like judging the execute permissions of a file on Linux, you can really do that. >>> 'w' in permission True >>> 'xx' in permission False >>> users=['jason','james','jzhou'] >>> raw_input ("enter your name:") in users enter your name:jzhou True

Example sequence membership:

database=[['jason','42'],['james','45'],['jzhou','22']] username=raw_input("Username:") age=raw_input("Age:") if [username,age] in database: print "OK,right" raw_input()

Built-in functions len, min, max

>>> numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> len(numbers) 10 >>> max(numbers) 10 >>> min(numbers) 1 >>>

List:

Lists are different from tuples and strings, lists are variable, and lists have many specialized methods.Strings cannot be modified like lists, but the list function in the list can be modified.Common uses of lists:

>>> list('hello') ['h', 'e', 'l', 'l', 'o'] >>> x=[1,1,1] >>> x[1]=2 #You can change the list to assign values to elements >>> x[2]=3 >>> x [1, 2, 3] >>> names=['james','jason','jzhou','liwear'] #You can delete elements from the list >>> del names[3] >>> names ['james', 'jason', 'jzhou'] >>> name=list('jzhou') >>> name ['j', 'z', 'h', 'o', 'u'] >>> name[2:]=list('1314') #Can be assigned in pieces >>> name ['j', 'z', '1', '3', '1', '4']

>>> numbers=[1,5] #Fragment assignment inserts new elements without replacing any elements >>> numbers[1:1]=[2,3,4] >>> numbers [1, 2, 3, 4, 5] >>> numbers[1:4]=[] #Delete elements that can also be disguised >>> numbers [1, 5]

The main methods of listing are append, count,extend,index,insert,pop,remove,reverse,sort. Simple uses are as follows:

>>> list=[1,2,3]

>>> list .append(4) # Append is used to append new objects to the end of the list

>>> list

[1, 2, 3, 4]>>> ['to','be','or','to'].count('to') #count counts the number of times an element appears in a list 2 >>> x=[[1,2],1,1,[2,1,[1,2]]] >>> x.count(1) 2 >>> x.count([1,2]) 1 >>> a=[1,2,3] >>> b=[4,5,6] >>> a.extend(b) #Extended appends multiple values of another sequence at the end of the list at once, expanding the original list >>> a [1, 2, 3, 4, 5, 6] #Note that unlike the join operation, the extension modifies the extend ed sequence, a, while the join only temporarily displays unchanged >>> a=[1,2,3] >>> b=[4,5,6] >>> a[len(a):]=b #It can also be extended by piecewise assignment, but it is not readable >>> a [1, 2, 3, 4, 5, 6] >>> sentence=['we','are','good','student'] >>> sentence.index ('are') #Index is used to find the index position of the first match of a value from the list 1 >>> numbers=[1,2,3,4,5,6,7] >>> numbers.insert(3,'four') #Insert is used to insert objects into a list, much like a chain table in a data structure >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7] >>> numbers=[1,2,3,4,5,6,7] >>> numbers[3:3]=['four'] #You can also use piecewise assignment, but it is not readable >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7] >>> x=[1,2,3] >>> x.pop() #The stack out operation, like the stack operation in the data structure, removes the last one in the list and returns the value of that element 3 >>> x [1, 2] >>> x.pop() 2 >>> x=[1,2,3] >>> x.append(x.pop()) #This operation is the same as push and pop in the data structure. It's interesting to append the value just out of the stack, and the final result is the original value. >>> x [1, 2, 3] >>> x=['to','be','or','not','to','be'] >>> x.remove ('be') #remove removes the first match for a value in the list >>> x #It is worth noting that the remove method is an in-situ change method with no return value, noting the difference from pop ['to', 'or', 'not', 'to', 'be'] >>> x=[1,2,3] >>> x.reverse () #Store the elements in the list backwards, noting that this method changes the list but does not return a value >>> x [3, 2, 1] >>> x=[4,5,6,7,1,2,3] >>> x.sort() #Sort is used to sort the list in place and also changes the value of the sequence but does not return a value >>> x [1, 2, 3, 4, 5, 6, 7] >>>

Note that all of the above methods, except count and index, can change the contents of the list.

In the case where the sort method modifies the list but does not return a value, it needs to be elaborated:

>>> x=[4,6,2,1,7,9] >>> y=x.sort() #Because x.sort() does not revert, y is not assigned a value >>> print y None >>>

(The non-reverting property of the sort function determines that subsequent operations, such as x.sort().reverse(), cannot be continued after it, but serted(x).reverse() is correct.)

>>> x=[4,6,2,1,7,9] >>> y=x[:] #Copy x to y first >>> y.sort() #Sort y >>> x [4, 6, 2, 1, 7, 9] >>> y [1, 2, 4, 6, 7, 9] >>> x=y>>> x [1, 2, 4, 6, 7, 9] >>> y [1, 2, 4, 6, 7, 9]

Another way to get a sorted copy of a list is to use the sorted function:

>>> x=[4, 6, 2, 1, 7, 9] >>> y=sorted(x) >>> x [4, 6, 2, 1, 7, 9] >>> y [1, 2, 4, 6, 7, 9]

The sorted function can be used for any sequence, but always returns a list:

>>> sorted("Python") #Sort by ASCII code by default ['P', 'h', 'n', 'o', 't', 'y']

If you want to drain some elements in reverse order, you can call the reverse function with the sort or sorted function first.Nested usage is powerful.

About advanced sorting: Elements can be sorted in a specific way, using the compare(x,y) custom comparison function, which returns negative values when x<y, positive values when x>y, and 0 when x=y.Once the function is defined, you can provide the sort method as a parameter.

>>> cmp(42,23) 1 >>> cmp(99,100) -1 >>> cmp(1,1) 0 >>> numbers=[5,2,6,7] >>> numbers.sort(cmp) #This mechanism will be introduced later >>> numbers [2, 5, 6, 7]

Tuples - Invariant Sequences

Tuples, like lists, are sequences. The only difference is that tuples cannot be modified, and strings do. Creating elements is simple. By separating values with commas, tuples are automatically created:

>>> 1,2,3 (1, 2, 3) >>> (1,2,3) (1, 2, 3) >>> (42,) # A comma means that it is a tuple, or parentheses (e.g. (42)) are useless (42,) >>> 3*(40+2) #This example illustrates the importance of commas, 42 and (42) are exactly the same 126 >>> 3*(40+2,) (42, 42, 42) >>>

tuple function:

The tuple function functions essentially the same as the list function: it converts a sequence as a parameter to a tuple.If the parameter is an array, it is returned as is:

>>> tuple([1,2,3]) (1, 2, 3) >>> tuple('abc') ('a', 'b', 'c') >>> tuple((1,2,3)) (1, 2, 3)

A tuple is actually an array, with no operations other than creation and access, similar to other types of sequence operations:

>>> x=1,2,3 >>> x[1] 2 >>> x[0:2] #A slice or tuple of a tuple, just like a slice or a list of lists (1, 2)

What is the meaning of tuples? First, tuples can be used as keys in maps, but not lists. Second, tuples exist as return values for many built-in functions and methods.As long as you don't involve modifying tuples, most of the time you will have the same basic functionality as lists.In general, lists satisfy all the requirements of a sequence better.

Summary of functions used: cmp(x,y), len (seq) (return sequence length), list (seq) (convert sequence to list), max(args), min(args), reverse (seq) (reverse iteration of sequence), sorted (seq) (return sorted list containing all elements of seq), tuple (seq) (convert sequence to tuple)