Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display grouped list of items from python list cyclically

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']
like image 500
SatyaV Avatar asked Aug 01 '20 01:08

SatyaV


4 Answers

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]])
like image 67
Paul Panzer Avatar answered Oct 12 '22 21:10

Paul Panzer


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]
like image 30
Aziz Avatar answered Oct 12 '22 19:10

Aziz


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)).

like image 5
GZ0 Avatar answered Oct 12 '22 20:10

GZ0


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]
like image 5
Gorisanson Avatar answered Oct 12 '22 19:10

Gorisanson