I have an array, given number of items in a group and number of groups, I need to print the array cyclically in a loop. Array-[1,2,3,4,5,6] Group- 4 Iterations- 7
Output should be:
['1', '2', '3', '4']
['5', '6', '1', '2']
['3', '4', '5', '6']
['1', '2', '3', '4']
['5', '6', '1', '2']
['3', '4', '5', '6']
['1', '2', '3', '4']
np.resize
is convenient here:
np.resize([1,2,3,4,5,6],(7,4))
# array([[1, 2, 3, 4],
# [5, 6, 1, 2],
# [3, 4, 5, 6],
# [1, 2, 3, 4],
# [5, 6, 1, 2],
# [3, 4, 5, 6],
# [1, 2, 3, 4]])
This is one way of doing it. I create a longer list composed of the input array twice, so something like this:
[1,2,3,4,5,6,1,2,3,4,5,6]
Then slice it from a starting index i
to i+N
(N
is the size of the group, 4 in this case).
a = [1,2,3,4,5,6]
N = 4 # Number of elements in a group
aa = a+a # create a list composed of the array 'a' twice
i = 0 # starting index
for loop in range(7):
# extract the elements from the doublelist
print(aa[i:i+N])
# The next starting point has to be within the range of array 'a'
i = (i+N)%len(a)
Output:
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
One solution is to combine itertools.cycle
with itertools.slice
.
from itertools import cycle, islice
def format_print(iterable, group_size, iterations):
iterable = cycle(iterable)
for _ in range(iterations):
print(list(islice(iterable, 0, group_size)))
format_print(range(1, 7), 4, 7)
Output:
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
If it is required to print string lists, cycle(iterable)
can be replaced with cycle(map(str, iterable))
.
You can try the following which uses itertools.cycle
:
import itertools
t = [1, 2, 3, 4, 5, 6]
number_of_elms_in_a_group = 4
iteration_number = 7
groups = []
group = []
for i, x in enumerate(itertools.cycle(t)):
if len(groups) >= iteration_number:
break
if i % number_of_elms_in_a_group == 0 and i != 0:
groups.append(group)
group = []
group.append(x)
# At this point,
# groups == [[1, 2, 3, 4], [5, 6, 1, 2], [3, 4, 5, 6],
# [1, 2, 3, 4], [5, 6, 1, 2], [3, 4, 5, 6],
# [1, 2, 3, 4]]
for group in groups:
print(group)
which prints
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
[5, 6, 1, 2]
[3, 4, 5, 6]
[1, 2, 3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With