Problem with rotating a two-dimensional array in python [duplicate] - python

This question already has answers here:
Rotating a two-dimensional array in Python
(8 answers)
Closed 1 year ago.
How to to make this array rotate by 90 degrees to right without using numpy.
multiarray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
auxiliaryArray = []
colLength = len(multiarray[0])
rowLength = len(multiarray)
for indexRow in range(len(multiarray)):
for indexCol in range(len(multiarray[0])):
auxiliaryArray[indexCol][rowLength - 1 - indexRow] = multiarray[indexRow][indexCol]
print(auxiliaryArray)
Error:
IndexError: list index out of range
Desired Output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

You can use zip on the reversed array:
auxiliaryArray = list(zip(*multiarray[::-1]))
or
auxiliaryArray = list(zip(*reversed(multiarray)))
output: [(7, 4, 1), (8, 5, 2), (9, 6, 3)]
If you need lists and not tuples:
auxiliaryArray = list(map(list, zip(*reversed(multiarray))))
output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]

This does it:
list(zip(*multiarray[::-1]))

Related

How to split an array into chunks of a given length in python? [duplicate]

This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 1 year ago.
What is the fastest and shortest method to turn this:
ids = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for example into this:
ids = [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
by giving the input 2 as the fixed length.
Of course there are some easy ways to make this but none of them occur to me as fast or pretty.
Why don't you try out a list comprehension?
Example:
[ids[i:i+2] for i in range(0,len(ids),2)]
Output:
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
bad but effective:
ids = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_ids = []
function = lambda x, y: [x, y]
for i in range(0, len(ids), 2):
try:
new_ids.append(function(ids[i], ids[i + 1]))
except IndexError:
new_ids.append(ids[i])
ids = new_ids
print(ids)

Connecting an array of numpys [duplicate]

This question already has answers here:
concatenate numpy arrays which are elements of a list
(2 answers)
Closed 2 years ago.
I have a list of numpys of the same length each. for example:
my_list = [np.array([2, 3, 5, 5]),
np.array([5, 4, 1, 4]),
np.array([8, 4, 5, 1]),
np.array([7, 4, 5, 1])]
I want to turn the list into 2d numpy:
[[2, 3, 5, 5],
[5, 4, 1, 4],
[8, 4, 5, 1],
[7, 4, 5, 1]]
The following code does perform the operation but in a sloppy manner.
The result is also not arranged in the desired order:
combined = []
for i in my_list :
if len(combined) == 0:
combined = i
else:
combined = np.vstack((i,combined))
print(combined)
What needs to be changed to get the desired result?
The most straightforward way
np.vstack(my_list)
or
np.concatenate(my_list).reshape(len(my_list),-1)
Simply doing np.array(my_list) can get the job done.

Union list of lists without duplicates

I have got list of lists. I need to get all combinations of that lists from 2 of N to N of N.
I'm searching for it with itertools.combinations. After this I got list of lists and I need to combine them without duplicates.
For example I have got array:
a = np.array([[1,4,7],[8,2,5],[8,1,4,6],[8,1,3,5],
[2,3,4,7],[2,5,6,7],[2,3,4,6,8],[1,3,5,6,7]])
I'm searching for all 3 elements combinations:
a2 = list(itertools.combinations(a, 3))
a2[:5]
[([1, 4, 7], [8, 2, 5], [8, 1, 4, 6]),
([1, 4, 7], [8, 2, 5], [8, 1, 3, 5]),
([1, 4, 7], [8, 2, 5], [2, 3, 4, 7]),
([1, 4, 7], [8, 2, 5], [2, 5, 6, 7]),
([1, 4, 7], [8, 2, 5], [2, 3, 4, 6, 8])]
The length of this array: 56.
I need to combine every list in this array without duplicates.
For exmple for a2[0] input:
([1, 4, 7], [8, 2, 5], [8, 1, 4, 6])
output:
[1, 2, 4, 5, 6, 7, 8]
And so all 56 elements.
I tried to do it with set:
arr = list(itertools.combinations(a,3))
for i in arr:
arrnew[i].append(list(set().union(arr[i][:3])))
But I had got error:
TypeError Traceback (most recent call last)
<ipython-input-75-4049ddb4c0be> in <module>()
3 arrnew = []
4 for i in arr:
----> 5 for j in arr[i]:
6 arrnew[i].append(list(set().union(arr[:n])))
TypeError: list indices must be integers or slices, not tuple
I need function for N combinations, that returns new combined array.
But I don't know how to do this because of this error.
Is there way to solve this error or another way to solve this task?
A small function which solves it:
def unique_comb(a):
return list(set(itertools.chain(*a)))
For example:
unique_comb(([1, 4, 7], [8, 2, 5], [8, 1, 4, 6]))
If you want to pass a list as an argument to the function, rather than a list inside a tuple, just remove the * (which unpacks the list).
If you want to apply it to the entire array in one statement without defining a function:
a3 = [list(set(itertools.chain(*row))) for row in a2]
Flatting a tuple of lists:
from itertools import chain
new_tuple = [ list(set(chain.from_iterable(each_tuple))) for each_tuple in main_tuple_coll ]
I think this might solve your problem.
Flatten list combinations
comb = []
for line in a2[:3]:
l = list(set([x for y in line for x in y]))
comb.append(l)
comb
[out]
[[1, 2, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 7, 8], [1, 2, 3, 4, 5, 7, 8]]
The issue with:
arr = list(itertools.combinations(a,3))
for i in arr:
arrnew[i].append(list(set().union(arr[i][:3])))
Is that i is not the index of the item but the item in the list itself.
What you need is:
import itertools
import numpy as np
a = np.array([[1,4,7],[8,2,5],[8,1,4,6],[8,1,3,5],
[2,3,4,7],[2,5,6,7],[2,3,4,6,8],[1,3,5,6,7]])
arrnew = []
for item in itertools.combinations(a,3):
arrnew.append(list(set().union(*item)))
The result arrnew contains 56 items. Some are equal but none contain duplicates.
I would suggest using sorted rather than list to ensure that the items in each combined list are in ascending order.

Zip list of list in python [duplicate]

This question already has answers here:
Transpose list of lists
(14 answers)
Closed 4 years ago.
I'm trying to create a matrix transpose function in Python. A matrix is a two dimensional array, represented as a list of lists of integers. For example, the following is a 2X3 matrix (meaning the height of the matrix is 2 and the width is 3):
A=[[1, 2, 3],
[4, 5, 6]]
To be transposed the jth item in the ith index should become the ith item in the jth index. Here's how the above sample would look transposed:
>>> transpose([[1, 2, 3],
[4, 5, 6]])
[[1, 4],
[2, 5],
[3, 6]]
>>> transpose([[1, 2],
[3, 4]])
[[1, 3],
[2, 4]]
How can I do this?
You can use zip with * to get transpose of a matrix:
>>> A = [[ 1, 2, 3],[ 4, 5, 6]]
>>> zip(*A)
[(1, 4), (2, 5), (3, 6)]
>>> lis = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> zip(*lis)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
If you want the returned list to be a list of lists:
>>> [list(x) for x in zip(*lis)]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
#or
>>> map(list, zip(*lis))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
If we wanted to return the same matrix we would write:
return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]
What this does is it iterates over a matrix m by going through each row and returning each element in each column.
So the order would be like:
[[1,2,3],
[4,5,6],
[7,8,9]]
Now for question 3, we instead want to go column by column, returning each element in each row.
So the order would be like:
[[1,4,7],
[2,5,8],
[3,6,9]]
Therefore just switch the order in which we iterate:
return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

How to transpose a matrix in python without zip [duplicate]

This question already has answers here:
Matrix Transpose in Python [duplicate]
(19 answers)
Closed 9 years ago.
I was wondering how you could change the user input in python into a list, or better yet, a matrix, just as you would convert it to an integer by using int(input).
>>> L = [[1,2,3], [4,5,6], [7,8,9]]
>>> [[x[i] for x in L] for i in range(len(L[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
or
>>> zip(*L)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
or
>>> import numpy as np
>>> L = np.arange(1, 10).reshape((3, 3))
>>> L
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> L.transpose()
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])
array([[1,2,3], [4,5,6], [7,8,9]]).T will do what you want, if you're using numpy.
list comprehensions should fit the bill quite nicely. Here's the general function:
def transpose(the_array):
return [[the_array[j][i] for j in range(0, len(the_array[i]))] for i in range(0, len(the_array))]

Categories