"Learning notes--python"python commonly used data structures

Source: Internet
Author: User
Tags data structures stdin in python
5 python common data Structures Table of Contents1 List 1.1 list uses 1.2 to use list as stack (stack) 1.3 as queue 1.4 function programming tools 1.5 list comprehensions 2 del statement 3 tuples and sequence 4 Sets 5 Dictionaries 6 Cycle Technology 7 more conditions Operation 8 comparison sequence operations 1 List use of the 1.1 ListList-related functions: Append,extend,insert,remove,pop,index,count,sort,reverse
>>> a
[3, 1, 2]
>>> b
[4, 7, 6, ten]
>>> a.append (5)
>>> a
[ 3, 1, 2, 5]
>>> a.extend (b)
>>> a
[3, 1, 2, 5, 4, 7, 6, ten]
>>> a.insert (0,9) 
  >>> a
[9, 3, 1, 2, 5, 4, 7, 6, ten]
>>> a.insert (1,8)
>>> a
[9, 8, 3, 1, 2, 5, 4, 7, 6, ten]
>>> a.insert (5,1)
>>> a
[9, 8, 3, 1, 2, 1, 5, 4, 7, 6, ten]
>& Gt;> a.remove (1)
>>> a
[9, 8, 3, 2, 1, 5, 4, 7, 6, ten]
>>> a.pop (0)
9
>&G T;> a
[8, 3, 2, 1, 5, 4, 7, 6, ten]
>>> a.pop ()
>>> a
[8, 3, 2, 1, 5, 4, 7 , 6]
>>> a.index (1)
3
>>> a.insert (2,6)
>>> a
[8, 3, 6, 2, 1, 5, 4, 7 , 6]
 >>> a.count (3)
1
>>> a.count (6)
2
>>> a.sort ()
> >> a
[1, 2, 3, 4, 5, 6, 6, 7, 8]
>>> a.reverse ()
>>> A [8, 7, 6, 6, 5
, 4, 3, 2 , 1]
>>> 
1.2 Use list as stack (stack)

Using the append above, the POP function can easily use the list as a stack. The stack has advanced features.

>>> stack = [5,2,8]
>>> stack.append (9)
>>> stack
[5, 2, 8, 9]
>>> Stack.append (1)
>>> stack
[5, 2, 8, 9, 1]
>>> stack.pop ()
1
>>> Stack
[5, 2, 8, 9]
>>> stack.pop ()
9
>>> Stack
[5, 2, 8]
1.3 list as a queue

The list is also easy to use as a queue, which is characterized by FIFO. However, this use is very inefficient. Because when you delete an element from the queue header, all subsequent elements are moved left. You can use Collections.deque to implement queues, which are dedicated to queues, and their design guarantees the efficiency of the team and out teams.

>>> from collections import deque
>>> queue = deque (["Linux", "Unix", "Windows"])
>> > Queue
deque ([' Linux ', ' Unix ', ' Windows '])
>>> queue.append ("Mac")
>>> queue
deque ([' Linux ', ' Unix ', ' Windows ', ' Mac '])
>>> queue.popleft ()
' Linux '
>>> Queue
deque ([' Unix ', ' Windows ', ' Mac '])
1.4 Functional Programming Tools

For list, there are three functions that are useful: filter,map,reduce filter (function,sequence) selects elements from a sequence that enable function functions to return True

F (x): return x 2!=0 and x 3!= 0
... 
>>> filter (F, Range (1,20))
[1, 5, 7, 11, 13, 17, 19]
Map (function,sequence) functions function to each element on the sequence, returning the corresponding value
F (x): Return x*2+1 ... 
>>> Map (F,range (1,10))
[3, 5, 7, 9, 11, 13, 15, 17, 19]

If the function has two parameters, then two sequences are required

F (x,y): return x + y
... 
>>> map (f,[1,5,2],[6,3,9])
[7, 8, 11]
Reduce (function,sequence) acts on the two function functions on the first two elements of sequence, and then the result and the next element as a function argument
F (x,y): return x + y
... 
>>> reduce (f,[1,2,3,4])
F(x,y): Return x*y
... 
>>> reduce (f,[1,2,3,4])
24
1.5 List comprehensions

The list comprehensions is a way to create a list, for example

>>> squares = [x**2 for x in [4,3,7]]
>>> squares
[9, $]
>>> [(x,y) for x i n [1,2,3] for y in [3,2,4] if x!= y]
[(1, 3), (1, 2), (1, 4), (2, 3), (2, 4), (3, 2), (3, 4)]

There are times when you can avoid writing a lot of code, and it's clear and readable, as well as the way in which you define a collection in math, and there's a way in Haskell. In addition, the goods can be nested to play

>>> matrix = [
... [1,2,3,4],
... [5,6,7],
... [8,9,10,11,12]
... ]
>>> Matrix
[[1, 2, 3, 4], [5, 6, 7], [8, 9, ten, one]]
>>> [[Row[i] for row in matrix] for I in range (3)]
[[1, 5, 8], [2, 6, 9], [3, 7, 10]]

Of course, this is only to reflect the characteristics of the list comprehensions, when the real play, we have more convenient:

>>> Zip (*matrix)
[(1, 5, 8), (2, 6, 9), (3, 7, 10)]
2 del statement
>>> a = [5,2,67,1,72,1,728]
>>> a
[5, 1, 1, 728]
>>> del a[0]
>&G T;> a
[2, 1, 1, 728]
>>> del A[1:3]
>>> a
[2,, 1, 728]
>>> Del a[:]
>>> a
[]
>>> del a
>>> a
traceback (most recent call last) :
  File "<stdin>", line 1, in <module>
nameerror:name ' a ' isn't defined
3 tuples and sequences

There is also a standard data structure for the sequence, tuples. The elements in the tuple cannot be modified. Although tuple and list look alike, they are used for different occasions, which we will introduce later.

>>> t = "Linux", "Unix", "Winx"
>>> t
(' Linux ', ' Unix ', ' Winx ')
>>> p = ("Ubuntu", "Arch", "FreeBSD")
>>> P
(' Ubuntu ', ' Arch ', ' FreeBSD ')
>>> t[0]
' Linux '
> >> t[0] = "*nix"
traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TYP Eerror: ' Tuple ' object does not support item assignment
>>> s = [1,2,3]
>>> s
[1, 2, 3]
  >>> S[0] = 9
>>> s
[9, 2, 3]

Tuple has packing and unpacking two concepts packing is:

>>> t = "Linux", "Unix", "FreeBSD"

Unpacking is:

>>> x, y, z = t
>>> x
' Linux '
>>> y
' unix '
>>> z
' FreeBSD
4 Sets

Python also has a data structure, Sets. A unordered set that holds a repeating element, often used for member testing, for eliminating duplicates, and so on. Sets supports the intersection, difference, and other operations of mathematical sets.

>>> os = [' Linux ', ' Windows7 ', ' FreeBSD ']
>>> oset = set (OS)
>>> oset
set ([' Windows7 ', ' FreeBSD ', ' Linux ']
>>> ' Linux ' in Oset
True
>>> ' Unix ' in Oset
False
>>> A = set (' SDKF;AHDF ')
>>> b = Set (' safj13325er ')
>>> A-b # is not in a B
set ( [' H ', ' K ', ' d ', '; ']
>>> A | B # in A or in B
set ([' R ', ' a ', ' e ', ' d ', ' f ', ' h ', ' K ', ' J ', ' 3 ', ' 1 ', ' s ', ' 2 ', ' 5 ', '; ']
>>> A & B # in A and in B
set ([' A ', ' s ', ' F '])
>>> a ^ B # in A or in B and not at the same time in A,b
set ([' E ', ' d ') , ' H ', ' K ', ' j ', ' 1 ', ' 3 ', ' 2 ', ' 5 ', '; ', ' R ']

Collection also supports comprehensions attributes

>>> a = {x for x with ' ABCDE ' if x not in ' Abe '}
>>> a
set ([' C ', ' d '])

However, it is important to note that you cannot use {} when defining a sets, but instead use the set () 5 dictionaries

Another useful data structure in Python is dictionary. It consists of two parts of Key:value, the key value can find the Value,key value is unique.

>>> Tel = {' Jack ': 123, ' Lucy ': 456}
>>> tel[' Lucy ']
456
>>> Tel
{' Jack ': 123, ' Lucy ': 456}
>>> tel[' lily ' = 789
>>> Tel
{' Lily ': 789, ' Jack ': 123, ' Lucy ': 456}
  
   >>> Tel.keys ()
[' Lily ', ' Jack ', ' Lucy ']
>>> ' Lily ' in Tel
True

  

Dictionary can be constructed directly from a sequence composed of (Key,value) using Dict. Dictionary can also be constructed by using comprehension methods.

>>> dict ([(' Linux ', 123), (' Unix ', 456)])
{' Unix ': 456, ' Linux ': 123}
>>> Dict (linux=826, unix=910)
{' Unix ': 910, ' Linux ': 826}
>>> {x:x*2+1 for x in (3,7,1)}
{1:3, 3:7, 7:15}
6 Circulation Technology

When we want to traverse a sequence, we can use subscript, value, enumerate () to complete

>>> for I, V in enumerate ([' Linux ', ' Unix ', ' Winx ']):
...     Print I, v ... 
0 Linux
1 Unix
2 Winx

When we want to traverse two or more sequences, we can use ZIP () to complete

>>> ask = [' name ', ' System ', ' editor ']
>>> answer = [' Steve ', ' Mac ', ' Emacs ']
>>> for Q , a in-zip (ask, answer):
...     print ' What is your {0}? It is {1}. '. Format (q,a) ... 
What is your name? It is Steve.
What is your system? It is Mac.
What is your editor? It is emacs.

If you want to traverse in reverse order, you can use reversed () to complete

>>> for I in reversed ([' Winx ', ' Unix ', ' Linux ']):
...     Print I ... 
Linux
Unix
winx

If you want to sort and then iterate, you can use sorted () to complete

>>> for I in sorted ([' Unix ', ' Linux ', ' Winx ']):
...     Print I ... 
Linux
Unix
winx

If you want to traverse a dictionary, you can use Iteritems () to complete

>>> system = {' Unix ': ' Second ', ' Linux ': ' A ', ' Winx ': ' Last '}
>>> to Key,value in System.iterit EMS ():
.     . Print key, value
... 
Unix second
Winx last
Linux
7 more conditions to operate

For while and if, conditional actions are more than just comparisons, and there are more available operations. In and not, you can determine whether an element is or not within a sequence of two objects is the same object comparison operation can be linked, for example a < b = c, to indicate a < b and b = C and the famous bool operation : And, or, not, they can match the comparison operation BOOL Precedence is lower than the comparison operation, where not priority is highest, or minimum 8 comparison sequence operations

Sequence objects can also be compared, and they are compared according to the Order of the dictionary sequence (lexicographical ordering)

>>> (1,2,3) < (1,2,4)
True
>>> (1,2,3,4) < (1,2,3)
False
>>> ( 1,2,3,-1) < (1,2,3)
False
>>> (1,2,3) = = (1.0,2.0,3.0)
True

Original link: http://docs.python.org/2/tutorial/datastructures.html
Related Article

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.