gman2020
gman2020

Reputation: 39

Rotating Arrays in Python

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.

Upvotes: 0

Views: 212

Answers (3)

foggynight
foggynight

Reputation: 73

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)

Upvotes: 1

Hadrian
Hadrian

Reputation: 927

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

Upvotes: 0

Prashy
Prashy

Reputation: 61

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]

Upvotes: 0

Related Questions