Python's for loop is one of the most commonly used statements in coder. If you simply loop through the container, you will lose a lot of good experience. Like the following:
for i in range(10):
print(i)
Python provides a lot of techniques for loops, these methods can make the code more concise and beautiful, this time I will take a look.
1. Enumerate() function
When traversing a non-numerical sequence, sometimes it is necessary to extract the elements and the index together, and then the enumerate()
function can be used .
enumerate()
The function accepts a sequence or iterator, and returns a tuple containing the elements and their index values.
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']>>> list(enumerate(seasons))[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
You can also start
specify the starting value of the sequence value by adjusting the parameters:
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
At this time, use the for loop to traverse enumerate()
the sequence wrapped by the function to get the elements and their index values:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe
2. Dictionary item() method
When traversing the dictionary, if you traverse the dictionary object directly, you can only get the keys in the dictionary:
>>> sample = {'a':1,'b':2,'c':3}
>>> for i in sample:
... print(i)
...
a
b
c
If you use the dictionary items()
method, you can output the key and the corresponding value at the same time:
>>> sample = {'a':1,'b':2,'c':3}
>>> for i in sample.items():
... print(i)
...
('a', 1)
('b', 2)
('c', 3)
3. The zip() function
zip()
The function receives one or more iterable objects, aggregates the elements corresponding to each iterable object, and returns an iterator of tuples.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
When looping in two or more sequences at the same time, you can use zip()
functions to match the elements one by one.
>>> color = ['white','blue','black']
>>> animal = ['cat','dog','pig']
>>> for i in zip(animal,color):
... print(i)
...
('cat', 'white')
('dog', 'blue')
('pig', 'black')
4. sorted() function
When you need to sort the list first and then loop through it, you need to use a sorted()
function.
sorted()
The function receives an iterable object and returns a sorted list.
In addition, the sorted()
function has two parameters: key and reverse
key specifies a function with a single parameter used to extract the key for comparison (for example ) from each element of iterable
key=str.lower
. The default value isNone
(Compare elements directly)
reverse is a Boolean value. If set
True
, each list element will be sorted in reverse order.
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
5. reversed() function
reversed()
The function is used to reversely arrange the elements in the iterable object and return a reverse iterator.
>>> list(reversed([2,5,3,9,6]))
[6, 9, 3, 5, 2]
The for loop traverses the reversed()
iterable object wrapped by the function, and the number can be retrieved in reverse.
>>> for i in reversed([2,5,3,9,6]):
... print(i)
...
6
9
3
5
2
to sum up:
Five tips for for loops, they are enumerate()、item()、zip()、sorted()、reversed()
, these methods and functions not only make the loop more concise, but also can be used in many other codes