In Python it is possible that a command for
Sure go through multiple sequences at the same time.
But before I say I’d better clarify a few things: (1) the for
in Python is not, in general, used for "counters". Since the for
always going through a sequence, the natural is to run through each element of a sequence, not the element index (and then, given the index, extract the element from the sequence). In other languages this construction usually takes the name of "for each":
for letra in "palavra":
print(letra)
instead of:
for i in range(len("palavra")):
letra = "palavra"[i]
print(letra)
E (2): being able to "see" at the same time a letter and the following letter will not help you with this particular issue problem - you will need two for
one inside the same.
Then, in Python, the command for
uses the element on which it will interact as an "iterator". That is, for item in minhalista:
will call the equivalent of iter(minhalista)
, and on the object (let’s call ITER) returned so will do the equivalent of next(ITER)
. When the call to next
fail (with an internal "Stopiteration" exception) for is terminated.
If the iterator used in for
return a sequence, the values returned by the sequence are distributed to the variables of the 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 one item of the internal sequence will be in b, and the other in c.
In the case of sequences, if you want to combine elements of them in the for
, there is convenient call zip
- which takes an element from each sequence and delivers so that it can be used in the:
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 take a letter and the next letter is possible to do:
a = "meu texto"
for letra1, letra2 in zip(a, a[1:]):
print(letra1, letra2)
(a[1:]
is simply string in a
from the index letter "1" to the end, that is, if the string is "word", in the first interaction the letters "p" and "a")
And, explained how it works in Python - for your problem you will need to simply:
for letra1 in "palavra":
for letra2 in "palavra":
# coparações e atribuições necessárias para detectar repetição.
You may also need the 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
Possible duplicate of two counters no for? Python
– Woss
You can post the full code?
– Laerte
kkk it is complicated to post it all here... because some fellow can see and copy something. After delivering it to the teacher, there is no problem kkkk. But then. this part does not relate directly to the others (only at the end). there comes a variable of the whole type (so I convert to string there. to use the index). All I need is to check if there are identical digits in the string
– fernanda