(Basic Python tutorial) learning notes | chapter 02nd | list and array

Source: Internet
Author: User

(Basic Python tutorial) learning notes | chapter 02nd | list and array

Chapter 2: List and array

------

In Python, the most basic data structure is a sequence. Each element is assigned a sequence number, that is, the sequence number of the element, that is, the index. Note: it must start from 0, the first digit is 0, the second digit is 1, and so on. python includes four common data structures: String, list, ancestor, and dictionary, or four sequences. The ancestor is an immutable sequence.

Main differences between list and ancestor

The list is variable, while the ancestor is immutable >>> list1 = ['Tom ', 40] So the ancestor is mainly used to store unchanged data >>>
>>> tuple1 = (130,131,132,133,134)>>> tuple1[0]=135Traceback (most recent call last):  File "
 
  ", line 1, in 
  
       tuple1[0]=135TypeError: 'tuple' object does not support item assignment>>> list = ['Tom',40]>>> list['Tom', 40]>>> list[0]='Jerry'>>> list['Jerry', 40]
  
 

For example, to create a record name and the ancestor of the age, you can:

>>> edward = ['Edward Gumby',40]>>> john   = ['John Smith',50]>>> database = [edward,john]>>> database[['Edward Gumby', 40], ['John Smith', 50]]
------

Common sequence operations:

Index slices add elements to delete elements update element search elements (check whether an element is a member of a sequence) sequence length maximum value minimum other built-in functions

------

Index

>>> Greeting = 'Hello World! '
>>> Greeting [0]
'H'
>>> Greeting [-1]
'! '

If you are only interested in the fourth digit of the year, you can do this:

>>> Fouth = raw_input ('year: ') [3]
Annual: 2008
>>> Fouth
'8'

# Filename: showmonth. pymonths = ['january ', 'february', 'march', '0000l', 'may', 'june', 'july', 'August ', 'September ', 'October ', 'november', 'decimal'] year = raw_input ('year:') month = raw_input ('month (1-12 ):') day = raw_input ('day (1-31): ') endings = ['st', 'nd ', 'RD '] + 17 * ['th'] + \ ['st', 'nd ', 'RD '] + 07 * ['th'] + \ ['st'] month_number = int (month) day_number = int (day) month_name = months [month_number-1] ordinal = day + endings [day_number] print month_name [: 3] + ''+ ordinal + ',' + year # output result D: \> python showmonth. pyYear: 2014 Month (1-12): 09Day (1-31): 13Sep 13th, 2014
------

Slice

>>> Tag = 'python Web site'
>>> Tag [9: 30]
'Http: // www.python.org'

>>> Tag [32:-4]
'Python website'

# Output the last three digits. to calculate the last digit, the next digit must be listed.
>>> Numbers [7: 10]
[8, 9, 10]
# Or directly:
>>> Numbers [7:]
[8, 9, 10]
# [:] Or [:] indicates all
>>> Numbers [-3:]
[8, 9, 10]
# Output in inverted order. The stride is-1, that is, from right to left.
>>> Numbers [-1:-4:-1]
[10, 9, 8]
# Output start three digits
>>> Numbers [: 3]
[1, 2, 3]
# Output all
>>> Numbers [:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Output all other statements
>>> Numbers [:]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example: Take the domain name in the http://www.something.com:

url = raw_input('Enter Url Here:')Enter Url Here:http://www.sohu.comprint "Domain is:" + url[11:-4]Domain is:sohu
------

Larger step size

>>> numbers[0:10:1][1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>> numbers[0:10:2][1, 3, 5, 7, 9]>>> numbers[::4][1, 5, 9]>>> numbers[8:3:-1][9, 8, 7, 6, 5]>>> numbers[10:0:-2][10, 8, 6, 4, 2]>>> numbers[0:10:-2][]>>> numbers[::-2][10, 8, 6, 4, 2]>>> numbers[5::-2][6, 4, 2]
# Sequence addition. Only values of the same type can be added.

>>> [1,2]+[3,4][1, 2, 3, 4]>>> 'Hello,'+'World!''Hello,World!'>>> [1,2]+'Hello'Traceback (most recent call last):  File "
 
  ", line 1, in 
  
       [1,2]+'Hello'TypeError: can only concatenate list (not "str") to list
  
 
------

Multiplication

# List Multiplication

>>> [0] * 10 [0, 0, 0, 0, 0, 0, 0, 0, 0] # string multiplication> 'python' * 5' pythonpythonpythonpython'
# Sequence Initialization
>>> seq = [None]*10>>> seq[None, None, None, None, None, None, None, None, None, None]
String multiplication example

# Print a sentence in the centered box with the correct width

sentence     = raw_input("Sentence:")screen_width = 80text_width   = len(sentence)box_width    = text_width +6left_margin  = (screen_width-box_width)/2print print ' '*left_margin + '+' +'-'*(box_width-2)   + '+'print ' '*left_margin + '| ' +' '*(text_width+2) + ' |'print ' '*left_margin + '| ' + sentence  + ' '*2 + ' |'print ' '*left_margin + '| ' +' '*(text_width+2) + ' |'print ' '*left_margin + '+' +'-'*(box_width-2)   + '+'printD:\Work\Python>python showmonth.pySentence:I Love Python                              +-----------------+                              |                 |                              | I Love Python   |                              |                 |                              +-----------------+
------

Membership:

Use the in operator number to determine the membership. If it is True or not, it is false:

>>> permissions='rw'>>> 'w' in permissionsTrue>>> 'x' in permissionsFalseusers=['root','test','guest']print raw_input('Name:') in usersD:\>python showmonth.pyName:rootTrue>>> subject = '$$$ Get Rich Now! $$$'>>> '$$$' in subjectTrue

database=[    ['root','1234'],    ['test','5678'],    ['book','9012']    ]user = raw_input('Enter user: ')puid = raw_input('Enter puid: ')if [user,puid] in database:    print 'Access Granted.'else:    print 'User or Pid not correct.'
------

Length, maximum value, minimum value

>>> N = [78,23, 64] >>> len (n); max (n); min (n) 37823 can compare multiple values >>> min (9, 3, 2, 5); max (9, 3, 2, 5) 29
------

List Function

# Convert a string to a list of individual characters> list ('hello') ['h', 'E', 'l', 'l ', 'o'] # convert a list of characters into a string >>> list1 = ['D', 'A', 'y'] >>> ''. join (list1) 'day'
------

Basic operations

# Update elements and assign values

>>> x = [0,1,2]>>> x[0]=8>>> x[8, 1, 2]
Note: you cannot assign values to a non-existent index, for example

>>> x[3]=3Traceback (most recent call last):  File "
 
  ", line 1, in 
  
       x[3]=3IndexError: list assignment index out of range
  
 
# Deleting an element

>>> names=['Jerry','John','Jack','Alice']>>> del names[3]>>> names['Jerry', 'John', 'Jack']
Note: del can delete Defined variables and functions.

>>> s = '1234'>>> def sum1(x,y):return x+y>>> sum1(1,2)3>>> del s; del sum1>>> sTraceback (most recent call last):  File "
 
  ", line 1, in 
  
       sNameError: name 's' is not defined>>> sum1(1,2)Traceback (most recent call last):  File "
   
    ", line 1, in 
    
         sum1(1,2)NameError: name 'sum1' is not defined
    
   
  
 

Partition assignment

# Assign values with the same length

>>> name=list('Perl')>>> name['P', 'e', 'r', 'l']>>> name[2:]='ar'>>> name['P', 'e', 'a', 'r']
# Assign values of different lengths

>>> name=list('Perl')>>> name['P', 'e', 'r', 'l']>>> name[1:]='ython'>>> name['P', 'y', 't', 'h', 'o', 'n']
# The partition can insert new elements without changing the original value.

>>> number = [1,5]>>> number[1:1]=[2,3,4]>>> number[1, 2, 3, 4, 5]
# Partitions can be inserted or deleted, which is equivalent to inserting 'empty slice'

>>> Number = [, 5] >>> number [] = [] >>> number [1, 5] is equivalent to del number []
------

List Method

Append: Add at the end

>>> num = [1,2,3]>>> num.append(4)>>> num[1, 2, 3, 4]
Count: calculates the number of times an element appears in the list.

>>> ['to','re','be','hi','to'].count('to')2>>> list1 = [[1,2],1,1,2,2,[2,1]]>>> list1.count(1)2>>> list1.count([1,2])1
Extend: Add a new list after the list

>>> a = [1,2,3]>>> b = [4,5,6]>>> a.extend(b)>>> a[1, 2, 3, 4, 5, 6]
The difference between extend and list addition: extend changes the value of the list to be added.

>>> a = [1,2,3]>>> b = [4,5,6]>>> a + b[1, 2, 3, 4, 5, 6]>>> a[1, 2, 3]
Of course, you can also insert data in slices, but the extend function is not as readable as the program.
>>> a = [1,2,3]>>> a[len(a):] = [4,5,6]>>> a[1, 2, 3, 4, 5, 6]
Index: finds the index value of the first matching item from the sequence.
>>> List1 = ['I', 'love', 'python', 'I, 'love', 'perl'] >>> list1.index ('love ') 1 >>> list1 [1] 'love' # If no, an exception not in the column is returned >>> list1.index ('java') Traceback (most recent call last ): file"
 
  
", Line 1, in
  
   
List1.index ('java') ValueError: 'java' is not in list
  
 
Insert: insert an entry at a specific position in the list.
>>> Numbers = [1, 2, 3, 5, 6] >>> numbers. insert (3, 'four ') >>> numbers [1, 2, 3, 'four', 5, 6] # You can also use slice to complete the process, but the readability is not as good as insert >>> numbers = [1, 2, 3, 5, 6] >>>> numbers [3] = ['four '] >>> numbers [1, 2, 3, 'four', 5, 6]

Pop: removes the elements from the list. The default value is the last one.

Note:

Pop is a function that can modify elements and return list values (except None). You can append (pop (0) to implement the FIFO function. You can also use insert (0 ...) use pop to implement deque objects in FIFO or collection

>>> X = [1, 2, 3] >>> x. pop () 3 >>> x [1, 2] >>> x. pop (0) 1 >>> x [2] pop can implement stack (FIFO: first-in-first-out, push, and pop) pop remain unchanged, push is equivalent to append >>> x = [1, 2, 3] >>> x. append (x. pop () >>> x [1, 2, 3]

Remove: removes the first element value in a match.

Note: Compared with pop, it is the first matching value for the operation, but no return item is removed> x = ['to', 'be', 'or', 'not ', 'to', 'be'] >>> x. remove ('be') >>> x ['to', 'or', 'not ', 'to', 'be']

Reverse: stores values in the list in reverse order

>>> X = [1, 2, 3] >>> x. reverse () >>> x [3, 2, 1] Note: To implement reverse iteration on a list, you can use reversed, but this function does not return a specific value, it is just an iteration, but it can be listed using the list () function.
  

>>> X = [1, 2] >>> list (reversed (x) [3, 2, 1]
Sort: sort the list in the original position
# The original list will be changed> x = [3, 1, 4, 2]> x. sort () >>> x [1, 2, 3, 4, 5] # note that the following is an error, and y returns a null value >>>> x =, 5] >>> y = x. sort () >>> yNone # The correct operation is to copy x and then perform operations on y >>> x =, 5] >>> y = x [:] >>> y. sort () >>> y [1, 2, 3, 4, 5]

Another way to sort the list is sorted ()

Note: If you plan to perform sort, reverse operations at the same time, x. sort (). reverse () is incorrect, and sorted (x). reverse () is correct.

>>> X = [, 5] >>>> y = sorted (x) >>> x [3, 1, 4, 2, 5] >>> y [1, 2, 3, 4, 5] Note: sorted can operate any sequence, returns a Sequence Value >>>> s = 'book' >>> sorted (s) ['B', 'k', 'O', 'O']

Advanced sorting:
Cmp, key, and reverse

# Cmp + sort # sort by sort in ascending order by default. If you want to implement a specific sort method, you can use cmp and sort to use >>> x = [5, 2, 7, 4]> x. sort (cmp) >>> x [2, 4, 5, 7] # key is a specific key value, for example, length, specific key value, for more information, see >>> x ['Welcome ', 'to', 'chengdu ','! '] >>> X. sort (key = len) >>> x ['! ', 'To', 'Welcome', 'chengdu'] # reverse, True, or False to determine whether reverse inversion is required >>> x = [9, 7, 2]> x. sort (reverse = True) >>> x [9, 7, 3, 2, 1]
------

Ancestor: Like a string, the ancestor is immutable, and the basic operations are the same as the list.

Note:

The print function is used in combination with the ancestor to store permanent values, such as ID card numbers and dates.

>>> X = [4, 3, 1, 2]
>>> X [0]
4
>>> X. pop ()
2
>>> X [1:]
[3, 1]

The following describes how to create a ancestor:

# Add a comma to any element> 1, 2, 3 (1, 2, 3)> 'hello', 'World' ('hello', 'World ') # Add () >>> (1, 2, 3) (1, 2, 3) # create an empty ancestor >>> ()() # create an element's ancestor> 1, (1,) >>> (1,) (1,) Example: the former is a value, and the latter is a ancestor, different returned objects> 3*(9 + 1) 30> 3*(9 + 1,) (10, 10, 10)

Tuple: transforms a sequence into a ancestor.

>>> l1=[1,2,3,4]>>> s1='python'>>> t1=(1,2,3)>>> tuple(l1);tuple(s1);tuple(t1)(1, 2, 3, 4)('p', 'y', 't', 'h', 'o', 'n')(1, 2, 3)
------

New functions in this Chapter

Cmp (x, y) compares two values
Len (seq) returns the length of the sequence
List (seq) converts a sequence to a list
Max (args) returns the maximum value of the sequence or parameter set.
Mix (args) returns the minimum value of a sequence or parameter combination.
Reversed (seq) performs reverse iteration on the sequence
Tuple (seq) converts the sequence to the ancestor

------





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.