Try to use the zip() function:
d=[] #This is done to avoid name 'd' is not defined
arr = [[1, 2, 3, 4], [5, 6, 7, 8]]
zipped = zip(arr[1], arr[0])
for i1,i2 in zipped:
d.append(i1/i2)
Answer from HydeNor on Stack OverflowTry to use the zip() function:
d=[] #This is done to avoid name 'd' is not defined
arr = [[1, 2, 3, 4], [5, 6, 7, 8]]
zipped = zip(arr[1], arr[0])
for i1,i2 in zipped:
d.append(i1/i2)
You can easily do this with numpy.
Extract the second row, and divide it by the first row element wise:
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
np.array(arr[1, :] / arr[0, :])
# [5. 3. 2.33333333 2. ]
If instead you want to do it with a for loop:
[arr[1][i] / arr[0][i] for i in range(len(arr[0]))]
Multidimensional array in Python - Stack Overflow
Access elements from nested array in python - Stack Overflow
nested Python numpy arrays dimension confusion - Stack Overflow
Nested array computations in Python using numpy - Stack Overflow
I want to create a 10x10 matrix of false booleans. I have done:
myMatrix = [[False] * 10] * 10
but I am finding that these rows are always the same. For example if I then do
myMatrix[0][3] = True
then every single row in my matrix will have the fourth boolean as True, which I don’t want - I want every row to be separate an unique.
Any help appreciated!
If you restrict yourself to the Python standard library, then a list of lists is the closest construct:
arr = [[1,2],[3,4]]
gives a 2d-like array. The rows can be accessed as arr[i] for i in {0,..,len(arr}, but column access is difficult.
If you are willing to add a library dependency, the NumPy package is what you really want. You can create a fixed-length array from a list of lists using:
import numpy
arr = numpy.array([[1,2],[3,4]])
Column access is the same as for the list-of-lists, but column access is easy: arr[:,i] for i in {0,..,arr.shape[1]} (the number of columns).
In fact NumPy arrays can be n-dimensional.
Empty arrays can be created with
numpy.empty(shape)
where shape is a tuple of size in each dimension; shape=(1,3,2) gives a 3-d array with size 1 in the first dimension, size 3 in the second dimension and 2 in the 3rd dimension.
If you want to store objects in a NumPy array, you can do that as well:
arr = numpy.empty((1,), dtype=numpy.object)
arr[0] = 'abc'
For more info on the NumPy project, check out the NumPy homepage.
To create a standard python array of arrays of arbitrary size:
a = [[0]*cols for _ in [0]*rows]
It is accessed like this:
a[0][1] = 5 # set cell at row 0, col 1 to 5
A small python gotcha that's worth mentioning: It is tempting to just type
a = [[0]*cols]*rows
but that'll copy the same column array to each row, resulting in unwanted behaviour. Namely:
>>> a[0][0] = 5
>>> print a[1][0]
5
I believe what you want to use is hstack:
a = np.zeros((2,4)) # 4 column vectors of length 2
b = np.ones((2,1)) # 1 column vector of length 2
c = np.hstack((a, b))
print c
# [[ 0. 0. 0. 0. 1.]
# [ 0. 0. 0. 0. 1.]]
Regarding the problem concatenating your a and b: This cannot be done in a obvious way. Concatenation means stacking on top of each other in an additional dimension. Your data does not fit on one another though...
Generally, nested NumPy arrays of NumPy arrays are not very useful. If you are using NumPy for speed, usually it is best to stick with NumPy arrays with a homogenous, basic numeric dtype.
To place two items in a data structure such that c[0] returns the first item,
and c[1] the second, a list (or tuple) such as c = [a, b] will do.
By the way, if you are using the statemodels package, then you can add a constant column with sm.add_constant:
import numpy as np
import statsmodels.api as sm
a = np.random.randint(10, size=(2,4))
print(a)
# [[2 3 9 6]
# [0 2 1 1]]
print(sm.add_constant(a))
[[ 1. 2. 3. 9. 6.]
[ 1. 0. 2. 1. 1.]]
Note however that if a already contains a constant column, no extra column is added:
In [126]: sm.add_constant(np.zeros((2,4)))
Out[126]:
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
Numpy treats its arrays as matrices, and resource_arr is not a (valid) matrix. In your case a python list is more suitable:
def sum_nested(l):
tmp = []
for element in l:
if isinstance(element, list):
tmp.append(numpy.sum(element))
else:
tmp.append(element)
return tmp
In this function we check for each element inside l if it is a list. If so, we sum its elements. On the other hand, if the encountered element is just a number, we leave it untouched. Please note that this only works for one level of nesting.
Now, if we run sum_nested([[2, 3], 4, 2, [1, 2]]) we will get [5 4 2 3]. All that's left is multiplying this result by the elements of rndm, which can be achieved easily using numpy:
def fitness_score(a, b):
return numpy.multiply(a, sum_nested(b))
Numpy is all about the non-jagged arrays. You can do things with jagged arrays, but doing so efficiently and elegantly isnt trivial.
Almost always, trying to find a way to map your datastructure to a non-nested one, for instance, encoding the information as below, will be more flexible, and more performant.
resource_arr = (
[0, 0, 1, 2, 3, 3]
[2, 3, 4, 2, 1, 2]
)
That is, an integer denoting the 'row' each value belongs to, paired with an array of equal size of the values themselves.
This may 'feel' wasteful when coming from a C-style way of doing arrays (omg more memory consumption), but staying away from nested datastructures is almost certainly your best bet in terms of performance, and the amount of numpy/scipy ecosystem that will actually be compatible with your data representation. If it really uses more memory is actually rather questionable; every new python object uses a ton of bytes, so if you have only few elements per nesting, it is the more memory efficient solution too.
In this case, that would give you the following efficient solution to your problem:
output = np.bincount(*resource_arr) * rndm
Numpy is your best friend as always :
>>> import numpy as np
>>> a = [[[ ['green', 'blue', 'red' ] ]]]
>>> print np.squeeze(a)
['green' 'blue' 'red']
The numpy function squeeze() remove all the dimensions that are 1 in your array.
def get_nested_list(a):
if len(a) == 1 and isinstance(a[0], list):
return get_nested_list(a[0])
return a
Examples:
>>> get_nested_list([[[ ['green', 'blue', 'red' ] ]]])
['green', 'blue', 'red']
>>> get_nested_list([[[[1, 2],[3]]]])
[[1, 2], [3]]