Advanced functions of list in python, pythonlist list

Source: Internet
Author: User

Advanced functions of list in python, pythonlist list

In all the data structures of Python, list is very important and convenient. This article mainly describes the advanced application of list. You can view the blog with basic knowledge.
This document is an English version of python. You can also view the English version:Https://docs.python.org/2/tutorial/datastructures.html

Use a list as a stack: # use a list like a stack

Stack = [3, 4, 5] stack. append (6) stack. append (7) stack [3, 4, 5, 6, 7] stack. pop () # Delete the last object 7 stack [3, 4, 5, 6] stack. pop () 6 stack. pop () 5 stack [3, 4]

Use a list as a queue: # use the list like 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 leaves 'Eric '> queue. popleft () # The second to arrive now leaves 'john'> queue # Remaining queue in order of arrivaldeque (['Michael ', 'terry', 'Graham '])

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

Filter (), map (), and reduce ().
1) filter (function, sequence )::
Filter data in the list sequence according to the function rules

> Def f (x): return x % 3 = 0 or x % 5 = 0... # f function defines integer object x. x is a multiple of 3 or 5> filter (f, range (2, 25) # filter [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

2) map (function, sequence ):
Map functions perform the same processing on the list sequence according to the function rules,
Here, sequence is not limited to lists, and tuples are also acceptable.

> Def cube (x): return x * x # Here we can use the method of x ** 3 for cube computing...> map (cube, range (1, 11) # perform cubic calculations on each object in the list [1, 8, 27, 64,125,216,343,512,729,100 0]

Note: The parameter list here is not fixed. It mainly depends on the number of parameters of the custom function. The map function can be transformed into def func (x, y) map (func, sequence1, sequence2) Example:

Seq = range (8) # define a list> def add (x, y): return x + y # User-Defined Function with two parameters...> map (add, seq, seq) # Use the map function. The last two parameters are the operands corresponding to the add function. If the list length is inconsistent, an error [0, 2, 4, 6, 8, 10, 12, 14]

3) reduce (function, sequence ):
The reduce function is used to operate the data in sequence according to the function. For example, the first and second numbers in the list are used to perform function operations. The result is as follows, keep repeating...
Example:

def add(x,y): return x+y...reduce(add, range(1, 11))55

List comprehensions:
Here we will introduce several applications in the list:
Squares = [x ** 2 for x in range (10)]
# Generate a list. The list is the result of square calculation after the list is generated by range (10.
[(X, y) for x in [1, 2, 3] for y in [3, 1, 4] if x! = Y]
# [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1 ), (3, 4)] A list is generated. Each item in the list is a tuple, which is composed of x and y. x is provided by list [, 3, y comes from [3, 1, 4] and satisfies the rule x! = Y.

Nested List Comprehensions:
It is difficult to translate. Let's give an example:

Matrix = [# define a matrix here... [1, 2, 3, 4],... [5, 6, 7, 8],... [9, 10, 11, 12],...] [[row [I] for row in matrix] for I in range (4)] # [1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]

It is difficult to nest two layers here. for a brief explanation: for matrix, for row in matrix, each row of the matrix is obtained, row [I] generates a list to retrieve the I (subscript) in the list of each row, And then I is from for I in range (4). This generates a list.

The del statement:
Delete the specified data in the list. For example:

> A = [-1, 1, 66.25, 333,333,123 4.5]> del a [0] # delete an element whose subscript is 0> a [1, 66.25, 333,333,123 4.5]> del a [] # delete an element with a subscript of 2 and 3 from the List> a [1, 66.25, 1234.5]> del a [:] # The delete all results are the same as del a> a []

Sets: Set

> 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 from two words...>>> a = set('abracadabra')>>> b = set('alacazam')>>> a                 # unique letters in aset(['a', 'r', 'b', 'c', 'd'])>>> a - b               # letters in a but 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 but not bothset(['r', 'd', 'b', 'm', 'z', 'l'])

Dictionaries: Dictionary

>>> Tel = {'Jack ': 4098, 'sape ': 4139 }>>> tel ['guid'] = 4127 # equivalent to adding data to the dictionary >>> tel {'sape ': 4139, 'guid': 4127, 'jack ': 4098 >>>> tel ['jack'] # Fetch data 4098 >>> del tel ['sape '] # delete data >>> tel ['irv'] = 4127 # modify data >>> tel {'guid ': 4127, 'irv': 4127, 'jack': 4098 }>>> tel. keys () # obtain all the key values of the dictionary ['guido', 'irv ', 'jack'] >>> 'guide' in tel # determine whether the key of the element is in the dictionary. True >>> tel. get ('irv') # get Data 4127

You can also use rules to generate a dictionary:

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

Enumerate ():Traversal element and subscript
The enumerate function is used to traverse the elements in the sequence and Their Subscript:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):...   print i, v...0 tic1 tac2 toe

Zip ():
Zip () is a built-in function of Python. It accepts a series of iteratable objects as parameters, and packs the corresponding elements of objects into tuple (tuples ), then, a list composed of these tuples is returned ). If the length of the input parameter is different, the returned list length is the same as the minimum length of the object in the parameter. Use the * operator to decompress the list unzip file ).

>>> questions = ['name', 'quest', 'favorite color']>>> answers = ['lancelot', 'the holy grail', 'blue']>>> 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.

Here is a simple example of zip:

>>> 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 (): reverse

>>> 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 )): # The set function is used here... print f... applebananaorangepear

Similar to other languages, python's set is a basic function that includes Link Testing and deduplication.

To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you 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 in words[:]: # Loop over a slice copy of the entire list....   if len(w) > 6:...     words.insert(0, w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']

The above is all the content of this article, hoping to help you learn.

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.