Criando helpers cíclicos – Python
- Postado por zrhans
- Categorias Blog, Programação, Python 3
- Data 08/05/2024
|
|
Value with index
The enumerate function returns a 2-item tuple of a number and an item. But what if you find yourself swapping the 2-item tuple values over and over throughout your code:
>>> indexes = {value: index for (index, value) in enumerate(iterable)}
If there was a looping helper that did the same thing as enumerate but the order of the tuple items were reversed, then we could do this:
>>> indexes = dict(with_indexes(iterable))
Let’s make that looping helper:
def with_indexes(iterable):
for i, item in enumerate(iterable):
yield (item, i)
Check out the result of using with_indexes:
>>> colors = [“purple”, “blue”, “green”]
>>> indexes = dict(with_indexes(colors))
>>> indexes
{‘purple’: 0, ‘blue’: 1, ‘green’: 2}
We’ve made a generator function that uses enumerate, but the resulting generator values have the 2 items in the tuple swapped.
Counting downward
Python’s built-in enumerate function is great for counting upward while looping… but what if you need to count downward?
You could simply negate each number that enumerate gives you… but if you find yourself doing this multiple times in your code, I’d consider making your own custom looping helper. We could call it denumerate:
def denumerate(iterable, start=0):
for n, value in enumerate(iterable, start=-start):
yield (-n, value)
The negating of start and negating of the n number is an interesting way to count “downward” while actually counting upward.
Try that generator function out yourself:
>>> for n, color in denumerate(colors, start=len(colors)):
… print(n, color)
…
3 purple
2 blue
1 green
|
|
|
Você também pode gostar
Notas de exercício em sala
George Boole

