0

I try to create a function which allows me to group an array into groups.

arr = [1,2,3,4,5,6,7,8,9,10,11]

group1 = [1,1,1,1,1,1,2,2,2,2,2] # build 2 groups
group2 = [1,1,1,1,2,2,2,2,3,3,3] # build 3 groups


newarr = []
for index, item in enumerate(arr):
    if index + 1 < len(arr) / 2:
        newarr.append(1)
    else:
        newarr.append(2)
        
print(newarr)
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]

This works somewhat, but I am not able to scale that function in any way, since I would have to add if and else clauses if I want 3, 4, x groups. Is there a function to dynamically create my desired results?

I know in R is a seq function, but I was not able to find something similar in Python.

3
  • Please share an example of input + expected output. Commented Sep 16, 2020 at 7:10
  • How do you define groups? should it have defined length, what should the occurrence of numbers be? if i see the occurrence of last number in group1 and group2, its length is one less than others.. Commented Sep 16, 2020 at 7:25
  • group1 and group2 are the expected outputs, arr is the input. @Yash Shah: Yes, that is the kind of a problem here. When you can not devide the array into equal length, I would like to assign to the first group Commented Sep 16, 2020 at 7:34

2 Answers 2

1

Are you looking for something like this?

arr = [1,2,3,4,5,6,7,8,9,10,11]
groups=2 #variable
newarr = []
for x in arr[:groups]:
    newarr+=[x]*(int(len(arr)/groups)+1)
newarr=newarr[:len(arr)]
print(newarr)
Sign up to request clarification or add additional context in comments.

Comments

0

Not the prettiest but faster than the pretty version below (it assumes that groups in group1/group2 are sequencial):

arr = [1,2,3,4,5,6,7,8,9,10,11]

group1 = [1,1,1,1,1,1,2,2,2,2,2] # build 2 groups
group2 = [1,1,1,1,2,2,2,2,3,3,3] # build 3 groups

groups = []
current_group = group1[0]
group = []
for i,v in zip(group1, arr):
    if i==current_group:
        group.append(v)
    else:
        groups.append(group)
        group = []
        group.append(v)
        current_group = i
groups.append(group)

yields (for group 1):

[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11]]

yields (for group 2):

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]

You can do it pretty, but its looping the table more, on the other hand it doesn't assume the groups to be sequencial:

[[ v for j,v in zip(group2,arr) if i == j] for i in set(group2)]

for same result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.