Advanced functions in python list list

This article is mainly to find out more advanced functions in python list list, little friends are interested can take a look
at all of the Python data structures, list plays an important role, and very convenient, this article is to explain the main advanced applications, the basics of list files can be viewed blog.
This article is a translation of the English version of python document, you can also view the English version: https: //docs.python.org/2/tutorial/datastructures.html

use a list as a stack: # Use the same list as the 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.pop() 
6
stack.pop() 
5
stack 
[3, 4]

use a list as a queue: # behaves like a queue using the list

> 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 arrival
deque(['Michael', 'Terry', 'Graham'])

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

filter (), Map (), and the reduce ().
. 1), filter (function, sequence) ::
filter data in accordance with the rules in the sequence listing function Function

> def f(x): return x % 3 == 0 or x % 5 == 0
... #f函数为定义整数对象x,x性质为是3或5的倍数
> filter(f, range(2, 25)) #筛选
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

2), Map (function, sequence):
Map function implementation according to the rules do the same function function list processing sequence,
here is not limited to sequence listing, may be the same tuple.

> def cube(x): return x*x*x #这里是立方计算 还可以使用 x**3的方法
...
> map(cube, range(1, 11)) #对列表的每个对象进行立方计算
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Note: This parameter list is not fixed, mainly depends on the number of custom function parameters, map function can be modified as: def func (x, y) map (func, sequence1, sequence2) Example:

seq = range(8)  #定义一个列表
> def add(x, y): return x+y #自定义函数,有两个形参
...
> map(add, seq, seq) #使用map函数,后两个参数为函数add对应的操作数,如果列表长度不一致会出现错误
[0, 2, 4, 6, 8, 10, 12, 14]

. 3), the reduce (function, Sequence):
the reduce function is a function Sequence data, in accordance with a function operation function, operation function, as will be the first number and the second number list, and the list of the results of the next data obtained for function operation, has been the cycle continues ...
For example:

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

List comprehensions:
This section introduces several applications list:
Squares = [X ** 2 for X in range (10)]
# generate a list, the result list is a list generated by the range (10) via a listing square calculation.
[(X, Y) for X in [l, 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)] where a list is generated for each of the tuples, each tuple is a list of x and y composition, x is [2,3] provided by the list, from y [3,1,4], and satisfies the rule x! = y.

Nested List Comprehensions:
Here is more difficult to translate, to illustrate it:

matrix = [          #此处定义一个矩阵
...   [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]]

Here two nested troublesome, briefly explain: matrix matrix, for row in matrix in each row of the matrix is ​​taken out, Row [i] is taken out the i-th (index) for each row in the list, to generate a list, then i is derived for i in range (4) this will generate a list of lists.

The del statement:
delete the 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的元素
>a
[1, 66.25, 1234.5]
>del a[:] #全部删除 效果同 del a
>a
[]

Sets: collection

> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)        # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit         # fast membership testing
True
>>> 'crabgrass' in fruit
False
 
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                 # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b               # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b               # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b               # letters in both a and b
set(['a', 'c'])
>>> a ^ b               # letters in a or b but not both
set(['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 the dictionary:

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

enumerate (): traversing element and subscripts
enumerate function is used to traverse the elements and their sequence index:

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

ZIP ():
ZIP () function is a built-in Python, which can be subjected to a series of iterations the object as a parameter, the corresponding element of the object packed into one tuple (tuples), and then returns a list composed of those tuples (list). If the length parameter passed ranging from the same list of parameters and the length of the shortest object is returned. No use * operator, may list unzip (decompression).

>>> 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.

About zip give a simple example of something: >>

> 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)):       #这里使用了set函数
...   print f
...
apple
banana
orange
pear

The set python and other similar language is a basic function, including testing and eliminating duplicate elements.

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']

Finally, we recommend a very wide python learning resource gathering, [click to enter] , here are my collection before learning experience, study notes, there is a chance of business experience, and calmed down to zero on the basis of information to project combat , we can at the bottom, leave a message, do not know to put forward, we will study together progress

Released five original articles · won praise 0 · Views 910

Guess you like

Origin blog.csdn.net/haoxun10/article/details/104663548