Display grouped list of items from python list cyclically
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))
.