Python Study Notes (2)

Source: Internet
Author: User
Tags date in numbers

Python Data Structure

To learn a language, the most basic and important thing is the data structure. In python, the most basic data structure is a sequence. It can also be understood as an array, but it seems to be more powerful than an array.

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

Index:

>>> Greeting = 'hello' >>> greeting [0] 'H' >>> greeting [-1] ==> starts from-1 instead of 0 when the opposite occurs' o' >>> digital = raw_input ("year: ") [3] year: 2013 >>> digital '3'

Index example:

>>> Months = ['january ', 'february', 'march', '0000l', \ 'may', 'june', 'july', 'August ', 'September ', 'October' \ 'November ', 'december'] # print the date in numbers based on the specified year, month, and 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 here the index should be reduced by 1 >>> ordinal = day + endings [day_num-1] >>> print month_name + ''+ ordinal + ', '+ yearMarch 30th, 2013 >>>

  Parts:

You can use indexes to access a single element. You can use shards to access a certain range of elements. fragments are implemented using two indexes 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 = [,] >>> numbers [] [4, 5, 6] >>> numbers [-3: -1] [8, 9]> numbers [-] # The leftmost index in the shard appears later than the index on the right of the shard in the sequence, the result is an empty sequence [] >>> numbers [-3:] # default to the last [8, 9, 10] >>> numbers [: 3] # [1, 2, 3]> numbers [:] # All [1, 2, 3, 4, 5, 6, 7 by default, 8, 9, 10]

Obviously, the implementation of the sharding operation requires two indexes as the boundary. The first index element is included in the shard, and the second is not included in the shard.

Fragment step size: the default step size is not written, which is 1. Fragment format: upper boundary: lower boundary: Step Size

>>> Numbers [] # The default step size is 1 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> numbers [] # Set the step size to 2 [1, 3, 5, 7, 9]> numbers [] # Set the step size to 3 [4]> numbers [: 4] [1, 5, 9] >>> numbers [8: 3:-1] # The step size cannot be 0, because it is not executed downward and can be a negative number. Run [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:

>>> [, 3] + [, 6] [1, 2, 3, 4, 5, 6] >>>, 3] + 'World' # The list and string are both sequences, but they cannot be connected together. Only the two sequences of the same type can be connected to Traceback (most recent call last ): file "<pyshell #141>", line 1, in <module> [, 3] + 'World' TypeError: can only concatenate list (not "str ") to list >>>

Sequential multiplication:

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

An empty list can be expressed in []. However, if you want to create a list that occupies ten elements, it does not include any useful and useful content. In this case, you need to use None. None is the built-in value of Python. initialize a list with a length of 10 as follows:

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

Sequence multiplication example: (run in script)

sentence=raw_input ("Sentence:")screen_width=60text_width=len(sentence)box_width=text_width+6left_margin=(screen_width-box_width)//2printprint ' ' * 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)  + '+'printraw_input()

The result is as follows:

  In Operator: Check whether a value is in the sequence

>>> Permission = 'rwx '# You can determine the execution permission of a file in Linux, you can really judge it like this >>> 'w' in permissionTrue >>> 'xx' in permissionFalse >>> users = ['jason ', 'James ', 'jzhou'] >>> raw_input ("enter your name:") in usersenter your name: jzhouTrue

Sequence member qualification example:

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 functionsLen, min, max

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

 List:

The list is variable and has many special methods, unlike tuples and strings. The string cannot be modified like a list, but the list function in the list can be modified. List common usage:

>>> 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 the elements in the List> del names [3]> names ['James', 'jason ', 'jzhou'] >>> name = list ('jzhou') >>> name ['J', 'z', 'h', 'O ', 'U'] >>> name [2:] = list ('000000') # sharding assignment >>> name ['J', 'z', '1 ', '3', '1', '4']
>>> Numbers = [] # You can insert a new element without replacing any element with a partition assignment. >>> numbers [] = [2, 3, 4] >>> numbers [1, 2, 3, 4, 5] >>> numbers [] = [] # You can also delete elements in disguise >>> numbers [1, 5]

  The list methods include append, count, extend, index, insert, pop, remove, reverse, and sort., Simple usage:

>>> List = [1, 2, 3]
>>> List. append (4) # append is used to append a new object to the end of the list.
>>> List
[1, 2, 3, 4]

>>> ['To', 'be', 'or', 'to']. count ('to') # count is used to count the number of times an element appears in the list. 2> x =, [1, 2] >>> x. count (1) 2> x. count ([]) 1 >>> a = [, 3] >>> B = [, 6] >>>. extend (B) # append multiple values of another sequence at the end of the list to extend the original list >>> a [1, 2, 3, 4, 5, 6] # note that this operation is different from the connection operation. extend modifies the extended sequence, that is, a, while the connection is only temporarily displayed and has not changed >>> a = [1, 2, 3] >>> B = [, 6] >>> a [len (a):] = B # It can be extended by multipart assignment, but the readability is not strong. >>> a [1, 2, 3, 4, 5, 6] >>> sentence = ['we', 'are', 'good ', 'Student ']> sentence. index ('all') # index is used to locate the index location of the first matching item 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 the list, which is very similar to the chain table operation in the 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 the multipart assignment method, but it is not readable >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7] >>> x = [1, 2, 3] >>> x. pop () # The output stack operation is the same as the stack operation in the data structure, that is, removing the last one in the list and returning the value of this 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 is interesting to append the value of the just-out stack, the final result is the original value >>> x [1, 2, 3] >>> x = ['to', 'be', 'or ', 'Not ', 'to', 'be']> x. remove ('be') # remove is used to remove the first matching item of a value in the List> x # It is worth noting that the remove method is the original position change method without return values, note the difference with pop: ['to', 'or', 'not ', 'to', 'be']> x =, 3]> x. reverse () # store the elements in the list in reverse direction. Note that this method changes the list but does not return values >>> x [3, 2, 1] >>> x =, 6, 7, 1, 2, 3] >>> x. sort () # sort is used to sort the list in the original position and change the value of the sequence, but no return value >>> x [1, 2, 3, 4, 5, 6, 7] >>>

Note that the preceding methods, except count and index, will change the content of the list.

When the sort method modifies the list but does not return a value, you need to elaborate:

>>> X = [,] >>> y = x. sort () # Because x. sort () does not return a value, so y is not assigned a value >>> print yNone >>>

Let's take a look at the correct method. In fact, we just need to split the steps: (the feature of the sort function does not return the value, so we cannot continue subsequent operations after it, such as x. sort (). reverse (), but serted (x ). reverse () is correct)

>>> X = [,] >>>> y = x [:] # copy x to y >>>> 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]

The sorted function is used to obtain sorted list copies:

>>> 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 in 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 export some elements in reverse order, you can use the sort or sorted function to call the reverse function. Nested functions are powerful.

About advanced sorting: elements can be sorted in a specific way. You can use the compare (x, y) custom comparison function, compare (x, y) the function returns a negative value when x <y, a positive value when x> y, and 0 when x = y. After defining this function, you can provide the sort method as a parameter.

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

Tuples-Immutable Sequence

The same as the list, tuples are also a sequence. The only difference is that tuples cannot be modified, and the same is true for strings. The creation element is very simple. When some values are separated by commas, The tuples are automatically created:

>>> 1, 2, 3 (1, 2, 3) >>> (1, 2, 3) (1, 2, 3) >>> (42 ,) # A comma indicates that it is a tuple, otherwise it will be useless (42,) with parentheses (e.g. (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 functions of the tuple function are basically the same as those of the list function: convert a sequence into a tuple as a parameter. If the parameter is an array, the parameter is returned as is:

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

Tuples are actually arrays. There are not many operations except creation and access. They are similar to other types of sequential operations:

>>> X = 1, 2, 3 >>> x [1] 2 >>> x [0: 2] # shard of the tuples or tuples, just like list shards or lists (1, 2)

So what is the significance of the existence of tuples? First, tuples can be used as keys in the ing, but the list cannot be used. Second, tuples exist as the return values of many built-in functions and methods. As long as you do not need to modify the tuples, the basic functions of the list are the same in most cases. In general, the list can better meet all the requirements for the sequence.

 

Summary of the 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 the sequence), sorted (seq) (returns a list of all elements of seq sorted), tuple (seq) (converts a sequence to a metagroup)

 

                                                                  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.