You could somehow hold it in a loop after the first iteration and store it in a variable and then continue on. So that in one variable there is a standard loop and in the other a previous loop?
example:
import numpy as np
for j in np.arange(0,5):
print(j)
0
1
2
3
4
5
6
i need example
0
1 0
2 1
3 2
4 3
5 4
6 5
just save the variable you want to print next, and print it before change it with the next one
num = 0
for j in np.arange(0,5):
print(num)
num = j
import numpy as np
for j in np.arange(0,7):
if j == 0:
print(j)
continue
print(j, j-1)
Use zip and itertools.tee:
itr1, itr2 = tee(np.arange(0, 5))
i, j = next(itr1), None
print(i, j)
for i, j in zip(itr1, itr2):
print(i, j)
outputs
0 None
1 0
2 1
3 2
4 3
The question is poorly worded, but here's a good basic iteration. It keeps track of the current variable, as well as saving it.
In [161]: alist = [1,3,6,9,12]
...: blist = []
...: latest = None
...: for item in alist:
...: blist.append(item)
...: print(latest, blist[-1])
...: latest = item
...: print(blist)
None 1
1 3
3 6
6 9
9 12
[1, 3, 6, 9, 12]
In the iteration, the current value is item, the previous is latest. blist[-1] is the last added item.
Related
I am trying to use a nested for loop to simply add two sets of numbers together respectively.
x=[1,2,3,4]
f=[0,1,2,3]
for i in x:
for j in f:
ans = i+j
ans2 = j
print(ans,ans2)
My output is
6 5
7 5
8 5
9 5
However, I want it to be
1 0
3 1
5 2
7 3
I'm not quite sure where i'm going wrong and any help would be appreciated.
You need to use the index into x to get the appropriate value of f to use as j. You can do this by iterating over the enumerated x:
x=[1,2,3,4]
f=[0,1,2,3]
for idx, i in enumerate(x):
j = f[idx]
ans = i+j
ans2 = j
print(ans,ans2)
Alternatively you could use zip and iterate both values at once:
for i, j in zip(x, f):
ans = i+j
ans2 = j
print(ans,ans2)
In both cases the output is:
1 0
3 1
5 2
7 3
Hello am a beginner to python and I have been stuck at this problem for awhile now. I want to start with 2 lists:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [a, b, c]
And write a function that will give me this output:
a
1
2
3
b
4
5
6
c
7
8
9
I have tried using nested for loops and a counter but I am unsure how to obtain the above result.
counter = 0
for i in list2:
print(i)
for j in list1:
print(j)
counter += 1
if counter == 3:
counter = 0
break
Any help would be appreciated!
Here's one possible way, closer to what you intended to write:
j = 0
for i in list2:
print(i)
for _ in range(3):
print(list1[j])
j += 1
Here's an option:
for i, v1 in enumerate(list2):
print(v1)
for v2 in list1[i*3:(i+1)*3]:
print(v2)
You don't need to make and update your own counters here. The built-in enumerate() function generates a counter for you and automatically updates it for each step of the loop. Then you can use list slicing to get the right three values of the inner list.
Try this:
for i in list2:
print(i)
# here you don't have to take it back to 0
counter = 0
for j in range(len(list1)):
# Use range to loop the list so you can cut it off later
# from the position you reach the third element
print(list1[j])
counter += 1
if counter == 3:
list1 = list1[j + 1:]
break
It outputs what you expect:
a
1
2
3
b
4
5
6
c
7
8
9
I can't explain the concept well at all, but I am trying to loop through a list using a nested loop, and I can't figure out how to avoid them using the same element.
list = [1, 2, 2, 4]
for i in list:
for j in list:
print(i, j) # But only if they are not the same element
So the output should be:
1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2
Edit as the solutions don't work in all scenarios:
The if i != j solution only works if all elements in the list are different, I clearly chose a poor example, but I meant same element rather than the same number; I have changed the example
You can compare the indices of the two iterations instead:
lst = [1, 2, 2, 4]
for i, a in enumerate(lst):
for j, b in enumerate(lst):
if i != j:
print(a, b)
You can also consider using itertools.permutations for your purpose:
lst = [1, 2, 2, 4]
from itertools import permutations
for i, j in permutations(lst, 2):
print(i, j)
Both would output:
1 2
1 2
1 4
2 1
2 2
2 4
2 1
2 2
2 4
4 1
4 2
4 2
Simply:
if i != j:
print(i, j)
I want to retain previous element in a for loop. Suppose I have a following loop
for i in range(5):
print i
0
1
2
3
4
I want to retain i=0 when i=1(previous value) in some variable. likewise i=2 when i=3 and so on. So,that I can use this previous value in a loop.
Put an initial value at the beginning, and then just reassign it at the end:
j = None
for i in range(5):
print "j:", j
print "i:", i
j = i
print
Output:
j: None
i: 0
j: 0
i: 1
j: 1
i: 2
j: 2
i: 3
j: 3
i: 4
Try this:
for i in range(5):
print i
if i > 0: print 'previous:\t%d' %(i-1)
It's not clear how you are planning on using the previous value but Python's itertools module recipe pairwise may work for you:
from itertools import tee, chain
def pairwise(iterable):
a, b = tee(iterable)
next(b, None)
return zip(a, b)
>>> for prev, curr in pairwise(range(5)):
... print(prev ,curr)
0 1
1 2
2 3
3 4
And you need curr to include 0:
>>> for prev, curr in pairwise(chain([None],range(5))):
... print(prev ,curr)
None 0
0 1
1 2
2 3
3 4
is there an easy way in python to cycle a variable in a given range?
For example:
Given a range(), I want a variable goes like this:
0 1 2 3 2 1 0 1 2 3... till some conditions are satisfied.
You want to cycle the sequence 0, 1, ..., n, n-1, ..., 1.
You can easily build this sequence using chain
from itertools import chain, cycle
def make_base_sequence(n):
base = range(n+1) # 0, ..., n
rev_base = reversed(range(1, n)) # n-1, ..., 1
return chain(base, rev_base) # 0, ..., n, n-1, ..., 1
for x in cycle(make_base_sequence(5)):
print(x)
Sample run:
In [2]: from itertools import chain, cycle
...:
...: def make_base_sequence(n):
...: base = range(n+1)
...: rev_base = reversed(range(1, n))
...: return chain(base, rev_base)
...:
...: for i, x in enumerate(cycle(make_base_sequence(5))):
...: print(x, end=' ')
...: if i > 20:
...: break
...:
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1
You want itertools.cycle(), see here:
https://docs.python.org/2/library/itertools.html#itertools.cycle
itertools.cycle is a good start. Else you can program it yourself:
cycle = [0,1,2,3,2,1]
i = 0
while some_condition:
value = cycle[i]
i = (i+1) % len(cycle)
#do stuff
import time
def cycle(range_):
num = -1
current = 0
a=time.time()
while 1:
print current
if current in (0, range_):
num*=-1
current += num
if time.time() - a > 0.002:
break
cycle(3)
output:
0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2 1 0 1 2 3 2
you need itertools.cycle:
demo:
>>> import itertools
>>> count = 0
>>> for x in itertools.cycle(range(3)):
... if count == 10:
... break
... print x,
... count += 1
...
0 1 2 0 1 2 0 1 2 0
import itertools
def f(cycle_range, condition_func):
sequence = range(cycle_range) + range(cycle_range)[-2:0:-1]
cycle_generator = itertools.cycle(sequence)
while not condition_func():
yield next(cycle_generator)
def condition_func():
"""Checks some condition"""
Essentially, you just want to loop and constantly check the condition. And each time yeild the next item from the cycle. Now, admittedly there are better ways to check a condition than a function call, but this is just an example.