Display grouped list of items from python list cyclically

Viewed 299

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']
10 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]])

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]

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]

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

If speed is an issue numpy can do this pretty well; however it will come at the cost of a memory

import numpy as np

arr = [1,2,4,5,6]
iteration = 7
group = 4

np.array([arr]*(group+2)).flatten().reshape(-1, group)[:it]

[[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]])

Another way to do it (quite obvious though). Repeat the array enough times using tile and then reshape it:

np.tile(array,Group*Iterations//array.size+1)[:Group*Iterations].reshape(Iterations,Group))

And if array is a list, first convert it to numpy array:

import numpy as np
array = np.array(array)

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]]

Here is another way of doing it without the use of any libraries:

array = [1, 2, 3, 4, 5, 6]

number_of_elements = 4
iterations = 7

iterations_groups = []
elements_group = []

for y in range(iterations):
    for i, x in enumerate(array):
        if len(iterations_groups) == iterations:
            break
        if len(elements_group) < number_of_elements:
            elements_group.append(x)
        else:
            iterations_groups.append(elements_group)
            elements_group = []
            elements_group.append(x)

for group in iterations_groups:
    print(group)

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]

I got this solution. Thank you all for posting answers, your answers helped me improve my knowledge.

from itertools import cycle

def sub_list(list_in, list_size, num_iter):
  cycle_list = cycle(list_in)
  for i in range(num_iter):
    print([str(next(cycle_list)) for i in range(list_size)])

sub_list([1,2,3,4,5,6], 4, 7)
 

Output is:

['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']

I can see a lot of solutions but I am giving you a solution without using any library. May be you will like it. I have created a circular linked_list using dictionary and then solved the problem.

output = []


def execute(grp, iteration, linked_list):
    key = 0
    for a in range(iteration):
        l = []
        for b in range(grp):
            value = linked_list[key]["value"]
            key = linked_list[key]["key"]
            l.append(value)

        output.append(l)
    return output


def get_linked_list(Array):
    linked_list = {}
    for count, a in enumerate(Array):
        if count == len(Array) - 1:
            linked_list[count] = {"key": 0, "value": a}
        else:
            linked_list[count] = {"key": count + 1, "value": a}
    return linked_list


Array = [11, 22, 33, 44, 55,66]
Group = 4
Iterations = 7
print(execute(Group, Iterations, get_linked_list(Array)))

You can do it just with slices.

a = [1,2,3,4,5,6]

for _ in range(7):
    print(a[0:4])
    a = a[4:] + a[0:4]
Related