Reputation: 445
There is a list s
and two variables m
and n
:
s = [3, 'abc', '123', 'def', '456', 'ghi', '789']
s[0]
is type int. It represents the number of times an iteration should occur to assign the following values to m and n.
Ex:
This list of s should be iterated 3 times as denoted by s[0]
. Each iteration should assign a new value from s to m and n.
First iteration, m and n should be assigned
m = 'abc'
n = '123'
Second iteration,
m = 'def'
n = '123'`
third iteration,
m = 'ghi'
n = '789'
What I have tried so far -
s = [3, 'abc', '123', 'def', '456', 'ghi', '789']
count = 0
i = 0
j = 2
while count < s[0]:
m = s[i+1]
n = s[j+1]
print(m)
print(n)
count += 1
i += 1
j += 1
My ouput is
abc
def
123
456
def
ghi
instead of
abc
123
def
456
ghi
789
Please help me to build the needed logic to get through this.
Upvotes: 0
Views: 366
Reputation: 30920
You could do this:
s = [3, 'abc', '123', 'def', '456', 'ghi', '789']
i = 1
count=1
while count<=s[0]:
m = s[i]
n = s[i+1]
print(m)
print(n)
i += 2
count+=1
the indices i, j must be incremented two by two, on the other hand, only one of them is needed, since the value of j at all times would be i + 1.
Upvotes: 1
Reputation: 558
Its convenient when you make it work where one variable is == 0. Then to assign m and n you can follow and understand example below:
count = 0
for itervar in [3, 41, 12, 9, 74, 15]:
count = count + 1
print 'Count: ', count
then
total = 0
for itervar in [3, 41, 12, 9, 74, 15]:
total = total + itervar
print 'Total: ', total
You can increase the number of iterations you want.
Upvotes: 0
Reputation: 1006
I think that we can simplify this by saying that in our loop the loop counter is equal to s[0]*2
. This way we can define loop step to be 2
. But this means that s[0]
has to be smaller or equal to (len(s) -1)/2
>>> s = [3, 'abc', '123', 'def', '456', 'ghi', '789']
>>> for i in range(1, s[0]*2, 2):
print(s[i])
print(s[i+1])
abc
123
def
456
ghi
789
Parameters to this range are:
So first loop we get i = 1
and we print indexes 1
and 2
, then the index becomes 3
and we print 3
and 4
, and so on.
Upvotes: 1
Reputation: 73460
You can just use an iterator and you won't have to manage indexes at all:
it = iter(s)
for _ in range(next(it)):
m, n = next(it), next(it)
print(m)
print(n)
Or using index access:
i, j = 1, 2
for _ in range(s[0]):
m, n = s[i], s[j]
print(m)
print(n)
i, j = i+2, j+2
Upvotes: 4