Slice a list
Taking part of a list of elements is a very common operation. For example, a list is as follows:
>>> L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Take the first 3 elements and what you should do.
Stupid way:
>>> [l[0], l[1], l[2]]
[' Adam ', ' Lisa ', ' Bart ']
The reason is stupid way is because of expansion, take the first n elements can not.
Take the first N elements, which are indexed as 0-(N-1) elements, you can use loops:
>>> r = []
>>> n = 3
>>> for I in Range (n):
... R.append (L[i])
...
>>> r
[' Adam ', ' Lisa ', ' Bart ']
For this type of operation that often takes a specified index range, the loop is tedious, so Python provides a slice (Slice) operator that simplifies the operation greatly.
Corresponding to the above problem, take the first 3 elements, with one line of code to complete the slice:
>>> L[0:3]
[' Adam ', ' Lisa ', ' Bart ']
L[0:3] Indicates that it starts at index 0 until index 3, but does not include index 3. The index 0,1,2, which is exactly 3 elements.
If the first index is 0, you can also omit:
>>> L[:3]
[' Adam ', ' Lisa ', ' Bart ']
You can also start with index 1 and take out 2 elements:
>>> L[1:3]
[' Lisa ', ' Bart ']
Use only one : , indicating from beginning to end:
>>> l[:]
[' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Therefore, l[:] Actually copied a new list.
A slice operation can also specify a third parameter:
>>> L[::2]
[' Adam ', ' Bart ']
The third parameter means that every n takes one, and the top L[::2] takes one out of each of the two elements, that is, a separate one.
Change list to tuple, slice operation is identical, only slice of result also become tuple.
Reverse Slice
For list, since Python supports l[-1] to take the penultimate element, it also supports reciprocal slices, try:
>>> L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
>>> l[-2:]
[' Bart ', ' Paul ']
>>> l[:-2]< c3/>[' Adam ', ' Lisa ']
>>> l[-3:-1]
[' Lisa ', ' Bart ']
>>> l[-4:-1:2]
[' Adam ', ' Bart ' ]
Remember that the index of the first element is minus 1. The reverse slice contains the starting index and does not contain an end index.
to slice a string
String ' xxx ' and unicode string u ' xxx ' can also be viewed as a list, each element being a character. Therefore, strings can also be sliced, but the result of the operation is still a string:
>>> ' ABCDEFG ' [: 3]
' ABC '
>>> ' ABCDEFG ' [-3:]
' EFG '
>>> ' ABCDEFG ' [:: 2]
' Aceg '
In many programming languages, many kinds of intercepting functions are provided for strings, but the goal is to slice the string. Python does not have an intercept function for a string, it is simple to slice one operation. What is an iteration
In Python, if a list or tupleis given, we can iterate through the list or tuple through a for loop, which we are iterating over (iteration).
In Python, iterations are done through for ... in, and many languages such as C or Java, where the iteration list is done by subscript, such as Java code:
For (i=0 i<list.length; i++) {
n = list[i];
}
As you can see, Python's for loops are more abstract than Java for loops.
because Python's for loop can be used not only on list or tuple, but also on any other iteration object.
Therefore, an iterative operation is for a set, whether the set is ordered or unordered, and we can always fetch each element of the collection in order by using the For loop.
Note : A collection is a data structure containing a set of elements that we have covered:
ordered collections : List,tuple,str and Unicode;
unordered collection : Set
unordered collection and has key-value pairs : dict
And an iteration is a verb, it refers to an operation, in Python, is a for loop.
The biggest difference between iterations and subscript access arrays is that the latter is a concrete iterative implementation, and the former only cares about iteration results and doesn't care about how the iterations are implemented internally. Index iterations
In Python, an iteration is always the element itself, not the index of the element.
For an ordered set, the element is indeed indexed. Sometimes we do want to get the index in the For loop.
The method is to use the enumerate () function :
>>> L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
>>> for index, name in enumerate (L):
... Print index, '-', name
...
0-adam
1-lisa
2-bart
3-paul
Using the enumerate () function, we can bind index and element name together in the For loop. However, this is not a special syntax for enumerate (). In fact, the enumerate () function puts:
[' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Into something like this:
[(0, ' Adam '), (1, ' Lisa '), (2, ' Bart '), (3, ' Paul ')]
Therefore, each element of an iteration is actually a tuple:
For T in enumerate (L):
index = t[0]
name = t[1]
print index, '-', name
If we know that each tuple element contains two elements, the for loop can be further shortened to:
For index, name in enumerate (L):
print Index, '-', name
This not only makes the code simpler, but it also has less than two assignment statements.
Thus, the index iterations are not really indexed access, but rather the enumerate () function automatically turns each element into a tuple such as index, element, and then iterates over the indexes and the elements themselves.
value of iterative dict
We have learned that the Dict object itself is an iterative object , with the for loop directly iterative dict, you can get dict each time a key.
What should we do if we want to iterate over the value of the Dict object.
The Dict object has a value () method that converts the dict to a list containing all of the values, so that we iterate over each of the dict:
D = {' Adam ': #, ' Lisa ': d.values, ' Bart ':
[v} print] # [n] [n] in
d.values ():
print V
# #
59
If you read the Python documentation carefully, you can also see that Dict has a itervalues ( ) method In addition to the values ( ) method, substituting the itervalues () method values () method, the iteration effect is exactly the same:
D = {' Adam ': #, ' Lisa ': d.itervalues, ' Bart ': ' The '
()
# <dictionary-valueiterator object at 0X106ADBB 50> for
v in D.itervalues ():
print v #
59
What is the difference between the two methods?
1. The values () method actually converts a dict into a list containing value.
2. However, the itervalues () method does not convert, and it takes value out of the dict in turn, so the Itervalues () method saves the memory needed to generate the list, rather than the values () method.
3. Print itervalues () finds that it returns a <dictionary-valueiterator> object, which shows that in Python the forLoop can act as an iterative object far more than List,tuple,str, Unicode,dict and so on , any iteration object can be used for a for loop, and internal how to iterate we usually don't care.
If an object says that it can iterate, then we iterate over it directly with a for loop, so that the iteration is an abstract data operation that does not require any data within the Iteration object.
key and value of iterative dict
We learned how to iterate over the key and valueof Dict, and then, in a for loop, can iterate over key and value at the same time. The answer is yes.
First, let's look at the value returned by the items () method of the Dict object:
>>> d = {' Adam ': #, ' Lisa ': D.items, ' Bart ': #} >>> print ' (' Lisa ', d ', ('
Adam ', 95), (' Bart ', 59)]
As you can see, the items () method converts the Dict object into a list containing tuple, and we iterate over the list to get key and value at the same time:
>>> for key, value in D.items ():
... Print key, ': ', value
...
lisa:85
adam:95
bart:59
and values () have a itervalues () similar, items () also have a corresponding iteritems (), Iteritems () does not convert dict to list, but in the iterative process constantly give Tuple, therefore, iteritems () does not occupy additional memory.
Build List
To generate the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we can use range (1, 11):
>>> Range (1, one)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
But if you want to generate [1x1, 2x2, 3x3, ..., 10x10] how to do it. Method one is loop:
>>> L = []
>>> for x in range (1, one):
... L.append (x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
But a loop is too cumbersome, and a list-builder can use a single line of statements instead of looping to generate the list above:
>>> [x * x for x in range (1, one)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
This notation is a Python-specific list-builder. With a list generation, you can generate a list in very concise code.
Write list generation, the element to be generated X * x into the front, followed by the For loop, you can create a list, very useful, more than a few times, you will soon be familiar with this syntax.
Complex Expressions
Iterations that use a for loop can iterate not only the normal list, but also the dict.
Assume the dict of the following:
D = {' Adam ': ' Lisa ': ' n ', ' Bart ': 59}
It can be turned into an HTML table by a complex list-generation:
TDS = [' <tr><td>%s</td><td>%s</td></tr> '% (name, score) for name, score in D.iteritems ()]
print ' <table> '
print ' <tr><th>name</th><th>score</th ><tr> '
print ' \ n '. Join (TDS)
print ' </table> '
Note: The string can be formatted by%, replacing %s with the specified parameter. The join () method of a string can concatenate a list into a string. Conditional Filtering
The For loop for the list generation can also be followed by an if judgment . For example:
>>> [x * x for x in range (1, one)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
If we only want even squared, without changing range (), we can add if to filter:
>>> [x * x for x in range (1, one) if x 2 = 0]
[4, 16, 36, 64, 100]
With the IF condition, the current element of the loop is added to the list only if the if is judged to be True.