0

Good afternoon,

May I please get help in solving an array rotation in Python? I wish to convert a 4 x 4 array into a 16 x 1 array. What I'm thinking is that, I would take each row (4 x 1), rotate it (1 x 4), and append each row rotation on each other until I reach 16 x 1. Would anyone know how to do this in Python? Any help would be appreciated, thank you.

5
  • I'ts a very bad question if you only ask for an answer and don't show what you have tried... Commented Aug 13, 2020 at 22:31
  • 2
    You have the algorithm steps. Show the coding problem you have. Commented Aug 13, 2020 at 22:32
  • 1
    Please provide a minimal reproducible example including sample data and code for what you've tried so far. Is this a list of lists, or an actual array, as in numpy? Commented Aug 13, 2020 at 22:33
  • 1
    Talking of "rotating" the array does not tally with how you then say that the "rotated" arrays are to be combined, because all that you are really doing is flattening the array. Is your input an actual numpy array, or a list of lists? Commented Aug 13, 2020 at 22:39
  • I apologize, it is bad form to not include code where I attempted a solution. Hadrian solved it (see below). Thank you everybody. Commented Aug 13, 2020 at 23:03

3 Answers 3

1

I'm a little unsure of exactly what you're looking for but:

example_arr = [
  [ 1, 2, 3 ],
  [ 4, 5, 6 ],
  [ 7, 8, 9 ]
]

# List Comprehension
new_arr = [ item for sublist in example_arr for item in sublist ]

# Long Form
new_arr = []
for sublist in example_arr:
  for item in sublist:
    new_arr.append(item)
Sign up to request clarification or add additional context in comments.

Comments

0
arr = [[0, 1, 2, 3],
    [4, 5, 6, 7],
    [8, 9, 10, 11],
    [12, 13, 14, 15]]
i = 0
new_arr = []
while i < len(arr):
    new_arr += arr[i]
    i += 1
arr = new_arr
del new_arr# no longer needed

2 Comments

Thank you, the code you provided works if instead of "arr = new_arr", you instead do "arr1 = new_arr". I just made it it's own variable. That solved my problem.
I gues you can use a for loop instead: for segment in arr:
0

Is this something you are looking for?

I/P :

[
  [ 0, 1, 2, 3 ],
  [ 4, 5, 6, 7 ],
  [ 8, 9, 10, 11 ],
  [ 12, 13, 14, 15 ],
]

O/P :

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

You can try this:

my_arr = [
  [ 0, 1, 2, 3 ],
  [ 4, 5, 6, 7 ],
  [ 8, 9, 10, 11 ],
  [ 12, 13, 14, 15 ],
]

new_arr = []
for row in my_arr:
    new_arr.extend(row)

print(new_arr)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

1 Comment

Thank you, I found that your code worked as I was hoping for.

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.