0

I am looking around a way to get the subset from an integer array based on certain range For example

Input
array1=[3,5,4,12,34,54]

#Now getting subset for every 3 element

Output
subset= [(3,5,4), (12,34,54)]

I know it could be simple, but didn't find the right way to get this output

Appreciated for the help

Thanks

Cloud_Hari
  • 49
  • 1
  • 5
  • 2
    Try writing some code. Post the code in your question. Don't worry if it's ugly or not quite correct, just try it. – John Zwinck Nov 28 '20 at 05:22
  • 1
    Does this answer your question? [How can you split a list every x elements and add those x amount of elements to an new list?](https://stackoverflow.com/questions/15890743/how-can-you-split-a-list-every-x-elements-and-add-those-x-amount-of-elements-to) – Vishnudev Krishnadas Nov 28 '20 at 05:26

3 Answers3

1

Consider using a list comprehension:

>>> array1 = [3, 5, 4, 12, 34, 54]
>>> subset = [tuple(array1[i:i+3]) for i in range(0, len(array1), 3)]
>>> subset
[(3, 5, 4), (12, 34, 54)]

Links to other relevant documentation:

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
1
arr = [1,2,3,4,5,6]
sets = [tuple(arr[i:i+3]) for i in range(0, len(arr), 3)]
print(sets)

We are taking a range of values from the array that we make into a tuple. The range is determined by the for loop which iterates at a step of three so that a tuple only is create after every 3 items.

Arnav Motwani
  • 707
  • 7
  • 26
1

you can use code:

from itertools import zip_longest
input_list = [3,5,4,12,34,54]
iterables = [iter(input_list)] * 3
slices = zip_longest(*iterables, fillvalue=None)
output_list =[]
for slice in slices:
    my_list = [slice]
    # print(my_list)
    output_list = output_list + my_list
print(output_list) 

You could use the zip_longest function from itertools https://docs.python.org/3.0/library/itertools.html#itertools.zip_longest

Salio
  • 1,058
  • 10
  • 21