In Python it is possible that a for
command traverses several sequences at a time.
But before saying this, you might want to clarify a few things: (1) for
in Python is not generally used for "counters". Since for
will always go through a sequence, the natural one is to go through each element of a sequence, not the index of the element (for later, given the index, extract the element of the sequence). In other languages this construction is usually called "for each":
for letra in "palavra":
print(letra)
instead of:
for i in range(len("palavra")):
letra = "palavra"[i]
print(letra)
And (2): being able to "see" at the same time one letter and the next letter will not help you with this problem of the particular issue - you will need two for
one within the same same. >
So, in Python, the for
command uses the element it will interact with as an "iterator". That is, for item in minhalista:
will call the equivalent of iter(minhalista)
, and in the object (let's call ITER) returned by it, it will make the equivalent of next(ITER)
. When the call to next
fails (with an internal "StopIteration" exception) the for is exited.
If the iterator used in for
returns a sequence, the values returned by the sequence are distributed to the variables of for
.
In the simplest case, if I have:
a = [[1,2], [3,4], [5,6]
for b, c in a:
print(b, c)
The loop will repeat 3 times and each time an item in the inner sequence will be in b, and the other in c.
For sequences, if you want to combine elements of them in for
, there is the convenient call zip
- which takes an element of each sequence and delivery so that it can be used in the for:
a = range(10)
b = range(10, 20)
for c, d in zip(a, b):
print(c,d)
In the case of a string, if you want to always pick up a letter and the next letter you can do:
a = "meu texto"
for letra1, letra2 in zip(a, a[1:]):
print(letra1, letra2)
( a[1:]
is simply the string in a
from the index letter "1" to the end, ie if the string is "word", the first interaction will use the letters "p" and "a")
And, explained how it works in Python - for your problem you will simply need:
for letra1 in "palavra":
for letra2 in "palavra":
# coparações e atribuições necessárias para detectar repetição.
You may also need enumerate
, another built-in Python that in addition to each element of a sequence you get the index of it:
for i, letra1 in enumerate("palavra):
for letra2 in "palavra"[i:]:
# codigo