List advanced functions in Python

Source: Internet
Author: User
Tags pear
This article is a detailed introduction of Python in the list of the advanced functions, interested in the small partners can refer to

Use a list as a stack: #像栈一样使用列表

stack = [3, 4, 5] stack.append (6) stack.append (7) Stack [3, 4, 5, 6, 7] Stack.pop () #删除最后一个对象 7 Stack [3, 4, 5, 6] stack.p OP () 6 Stack.pop () 5 Stack [3, 4]

Use a list as a queue: #像队列一样使用列表

> from Collections import deque #这里需要使用模块deque > Queue = deque (["Eric", "John", "Michael"]) > Queue.append ("Terry"      # Terry arrives> queue.append ("Graham")     # Graham Arrives> Queue.popleft () # The first to         arrive now le Aves ' Eric ' > Queue.popleft ()         # The second to arrive now leaves ' John ' > Queue              # Remaining queue in order of arr Ivaldeque ([' Michael ', ' Terry ', ' Graham '])

Three built-in functions: three important built-in functions

Filter (), map (), and reduce ().
1), filter (function, sequence)::
Filter data in list sequence by rules for function functions

> Def f (x): return x% 3 = = 0 or x 5 = = 0 ... #f函数为定义整数对象x, the X property is a multiple of 3 or 5 > filter (F, Range (2)) #筛选 [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

2), map (function, sequence):
The map function implements the same processing of list sequence as the rules of function functions.
Here sequence is not limited to the list, the tuple is also available.

> Def cube (x): Return x*x*x #这里是立方计算 can also use X**3 method ...> Map (cube, range (1, one)) #对列表的每个对象进行立方计算 [1, 8, 27, 64, 125, 21 6, 343, 512, 729, 1000]

Note: The parameter list here is not fixed, the main view is the number of parameters of the custom function, the map function can be transformed to: def func (x, y) map (Func,sequence1,sequence2) Example:

Seq = Range (8)  #定义一个列表 > Def add (x, y): Return x+y #自定义函数, two parameters ...> map (add, seq, seq) #使用map函数, and the latter two operands corresponding to the function add Error if the list length is inconsistent [0, 2, 4, 6, 8, 10, 12, 14]

3), reduce (function, sequence):
The Reduce function function is to sequence the data in, according to function functions, such as the first number of the list and the second number of function operations, the resulting results and the list of the next data function operation, has been circulating ...
Example:

def add (x, y): Return x+y...reduce (Add, Range (1, 11)) 55

List comprehensions:
Here are a few applications of the list:
Squares = [x**2 for x in range (10)]
#生成一个列表, the list is the result of a squared calculation of the list generated by list range (10).
[(x, Y) for x in [All-in-A-z] for y in [3,1,4] if x! = y]
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] Here is a list, each item of the list is a tuple, each tuple is composed of x and Y, X is provided by the list [three-to-one], y is from [3,1,4], and satisfies The law x!=y.

Nested List comprehensions:
It is difficult to translate here, just to illustrate it:

Matrix = [          #此处定义一个矩阵 ...   [1, 2, 3, 4],...   [5, 6, 7, 8],...   [9, ten, one, one],...] [[Row[i] for row under matrix] for I in range (4)]#[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]

Here two layers of nesting is more troublesome, briefly explain: to the Matrix Matrix,for row in the matrix to take out each row of matrices, Row[i] to take out the table of each row I (subscript), generate a list, and then I is from for I in range (4) This generates a list of lists.

The DEL statement:
To delete a list of specified data, for example:

> A = [-1, 1, 66.25, 333, 333, 1234.5]>del a[0] #删除下标为0的元素 >a[1, 66.25, 333, 333, 1234.5]>del A[2:4] #从列表中删除下标为 2,3 elements >a[1, 66.25, 1234.5]>del a[:] #全部删除 effect with del a>a[]

Sets: Collection

> basket = [' apple ', ' orange ', ' apple ', ' pear ', ' orange ', ' banana ']>>> fruit = set (basket)        # Create a set Without duplicates>>> fruitset ([' Orange ', ' pear ', ' apple ', ' banana ']) >>> ' orange ' in fruit         # fast Membership testingtrue>>> ' Crabgrass ' in fruitfalse>>> # demonstrate set operations on unique letters FR Om words...>>> a = set (' Abracadabra ') >>> B = Set (' Alacazam ') >>> a                 # unique letters in a Set ([' A ', ' R ', ' B ', ' C ', ' d ']) >>>-B               # Letters in a and not in bset ([' R ', ' d ', ' B ']) >>> a | b
  
   # letters in either A or bset ([' A ', ' C ', ' R ', ' d ', ' B ', ' m ', ' Z ', ' l ']) >>> A & B               # Letters in both A and bSET ([' A ', ' C ']) >>> a ^ b               # Letters in a or B and not bothset ([' R ', ' d ', ' B ', ' m ', ' Z ', ' l '])
  

Dictionaries: Dictionary

>>> Tel = {' Jack ': 4098, ' Sape ': 4139}>>> tel[' guido '] = 4127 #相当于向字典中添加数据 >>> tel{' sape ': 4139,  ' Guido ': 4127, ' Jack ': 4098}>>> tel[' Jack '] #取数据4098 >>> del tel[' Sape '] #删除数据 >>> tel[' irv '] = 4127   #修改数据 >>> tel{' Guido ': 4127, ' Irv ': 4127, ' Jack ': 4098}>>> Tel.keys ()    #取字典的所有key值 [' Guido ', ' Irv ', ' Jack ']>>> ' Guido ' in Tel #判断元素的key是否在字典中True >>> tel.get (' Irv ') #取数据4127

You can also use rules to generate dictionaries:

>>> {x:x**2 for x in (2, 4, 6)}{2:4, 4:16, 6:36}

Enumerate (): traversing elements and subscripts
The enumerate function iterates through the elements in the sequence and their subscripts:

>>> for I, V in enumerate ([' Tic ', ' tac ', ' toe ']):   ... Print I, v ... 0 Tic1 Tac2 Toe

Zip ():
Zip () is an intrinsic function of Python that takes a series of iterated objects as parameters, packages the corresponding elements in the object into tuple (tuples), and then returns a list of these tuples. If the length of the passed parameter is not equal, the length of the returned list is the same as the object with the shortest length in the parameter. Using the * operator, you can unzip the list (unzip).

>>> questions = [' name ', ' Quest ', ' Favorite color ']>>> answers = [' Lancelot ', ' The Holy Grail ', ' Blue ']& Gt;>> for Q, A in zip (questions, answers): ...   print ' What is your {0}? It is {1}. '. Format (q, a) ... What is your name? It is Lancelot. What is your quest? It is the Holy Grail. What is your favorite color? It is blue.

For a simple example of zip-lift:

>>> a = [1,2,3]>>> b = [4,5,6]>>> c = [4,5,6,7,8]>>> zipped = Zip (A, b) [(1, 4), (2, 5), (3, 6)] >>> Zip (a,c) [(1, 4), (2, 5), (3, 6)]>>> zip (*zipped) [(1, 2, 3), (4, 5, 6)]

Reversed (): Invert

>>> for I in Reversed (xrange (1,10,2)): ...   Print I ...

Sorted (): Sort

> basket = [' apple ', ' orange ', ' apple ', ' pear ', ' orange ', ' banana ']> for F in sorted (set (basket)):       #这里使用了set函数. .   Print F...applebananaorangepear

Python's set is similar to other languages, and is a basic feature that includes relationship testing and de-duplication elements.

To change a sequence you be iterating over and inside the loop (for example to duplicate certain items), it's recommen Ded that's first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>> words = [' cat ', ' window ', ' Defenestrate ']>>> for W "words[:]: # Loop over a slice copy of the Enti Re list ....   If Len (w) > 6:     ... Words.insert (0, W) ...>>> words[' defenestrate ', ' Cat ', ' window ', ' defenestrate ']

The above is the whole content of this article, I hope that everyone's study has helped.

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.