Slice
use only one: to indicate from beginning to end:
>>> L[:][‘Adam‘, ‘Lisa‘, ‘Bart‘, ‘Paul‘]
The slice operation can also specify a third parameter: The third parameter indicates that each n takes one, and the top L[::2] takes one out of every two elements, that is, one by one.
Change the list to a tuple, the slice operation is exactly the same, but the result of the slice becomes a tuple.
Iteration
The iterative operation is for a collection, regardless of whether the collection is ordered or unordered, we can always use the For loop to take each element of the collection in turn.
Note: A collection refers to a data structure that contains a set of elements that we have covered:
1 ordered set: List,tuple,str and Unicode;
2 Unordered Collection: Set
3 unordered set and with Key-value pair: dict
Example: Use the For loop to iterate through the algebraic column 1-100 and print a multiple of 7.
for i in range(1, 100)[6::7]: print i
In Python, iterations are always taken out of the element itself, not the index of the element. You want to take the index out
Enumerate () function
>>> L = [‘Adam‘, ‘Lisa‘, ‘Bart‘, ‘Paul‘]>>> for index, name in enumerate(L):... print index, ‘-‘, name... 0 - Adam1 - Lisa2 - Bart3 - Paul
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
The index iteration is not really indexed, but instead the enumerate () function automatically turns each element into a tuple of (index, Element) and iterates over the index and the element itself.
The values () method actually converts a dict to a list containing value.
However, the Itervalues () method does not convert, and it takes value from Dict in turn during the iteration, so the Itervalues () method saves the memory needed to generate the list, compared to the values () method.
Print itervalues () found it returns a
If an object says that it can iterate, then we iterate it directly with a for loop, which is an abstract data operation that does not require any data inside the iteration object.
Use the 3-layer for-loop list generation to find the symmetric 3-digit number. For example, 121 is the number of symmetries, since right-to-left is reversed or 121.
Pay attention to three ways of thinking
L=[]for x in range(1,10): for y in range(10): for z in range(1,10): if x==z : L.append(100*x+10*y+z)print Lprint [100 * x + 10 * y + z for x in range(1, 10) for y in range(10) for z in range(10) if x==z]print [x for x in range(100,1000) if str(x)[0]==str(x)[-1]]
Python (iii)