I have a function that takes in any 2-d array and return a 2-d array (the same format as the array being implemented) but the values are squared.
i.e [[1,2],[3,4]] -----> [[1,4],[9,16]]
my code so far:
m0 = [[1,2],[3,4]]
empty_list = []
for x in m0:
for i in x:
empyt_list.append(x**2)
This gives me a 1-d array but how would i return a 2-d array as the imputed value?
You can make a recursive function to handle any depth of nested lists:
def SquareList(L):
if type(L) is list:
return [SquareList(x) for x in L]
else:
return L**2
Example:
> print(SquareList([1,[3],[2,[3]],4]))
[1, [9], [4, [9]], 16]
Working with an outer list
The point is that you will need an extra list outside to store the columns. So we can introduce temporary lists we build up and add as rows:
m0 = [[1,2],[3,4]]
result = []
for sublist in m0:
row = []
for item in sublist:
row.append(item**2)
result.append(row)
Notice that we here iterate over the items of the sublist.
Using list comprehension
We can however write this more elegantly with list comprehension
result = [[x*x for x in sublist] for sublist in m0]
Note: if you have to square a number x, it is usually more efficient to use x * x, then to write x ** 2.
Using numpy (for rectangular lists)
In case the list is rectangular (all sublists have the same length), we can use numpy instead:
from numpy import array
a0 = array(m0)
result = a0 ** 2
You can just do this by a list comprehension:
empty_list = [[m0[i][j]**2 for j in range(len(m0[i]))] for i in range(len(m0))]
Or like your Codestyle:
empty_list = m0
for i in range(len(m0)):
for j in range(len(m0[i])):
empty_list[i][j] = m0[i][j] ** 2
Your problem is that you never created a 2D-list and you just append the values on the created 1D-list.
Related
I need to write this code where I take a list that has lists in it and takes in the ints in those lists and divide them by 2 and then return a new list that contains the lists with the divided ints
Here's what I came up with. I just can't seem to get a list that contains lists in it
def div_mat_by_scalar(mat, alpha):
mat2=[]
for i in range(len(mat)):
for j in range(len(mat[i])):
a = mat[i][j]//alpha
mat2.append(a)
return mat2
mat1 = [[2, 4], [6, 8]]
print(div_mat_by_scalar(mat1,2))
this prints [1,2,3,4] but I want [[1,2],[3,4]]
You need to append to a nested list, not the main list.
def div_mat_by_scalar(mat, alpha):
mat2=[]
for row in mat:
row2 = []
for el in row:
a = el//alpha
row2.append(a)
mat2.append(row2)
return mat2
Or use list comprehensions:
def div_mat_by_scalar(mat, alpha):
return [[el//alpha for el in row] for row in mat]
You're appending every element to the list. Bamar's answer is great if your mat is always two dimensional, but if you want to generalize this function to any number dimensions, you may want to adopt a recursive approach:
def div_mat_by_scalar(mat, alpha):
result = []
for elem in mat:
if isinstance(elem, list):
result.append(div_mat_by_scalar(elem, alpha))
else:
result.append(elem // alpha)
return result
I am trying to iterate over a list of lists of lists... of list of pair of coordinates in python and I want to sum a value to each of these pair of coordinates but I also want to keep the structure.
I think an example is worth more than a thousand words so:
coordinates = [[[-15.418887, 28.180395], [-15.418887, 28.180395]],
[[-15.794088, 28.018681], [-15.794088, 28.018681]]]
This is a very basic example but is not the real case. In the real each of the list has variables lengths except for the pair of coordinates. So maybe there are 4 lists until the list of list of pair coordinates or it could be 3, it is variable
I want to add 3 (for example) to each of these coordinates but keeping the original structure ( I don't want to flat the list of lists of list ....)
Maybe this is useful for trying to answer the question:
I have a geojson file and I want to move a feature ( a region) to another place. To do this I am trying to sum a constant value to latitude and longitude to each coordinate of the region
I think this could be done using recursion but I am not sure how
Any help is appreciated.
You can use a recursive function to handle the general case. Just check if you have a list and recurse, otherwise return the result of the addition:
def add_to_list(l, n):
if not isinstance(l, list):
return l + n
return [add_to_list(sub, n) for sub in l]
coordinates = [[[-15.418887, 28.180395], [-15.418887, 28.180395]],[[-15.794088, 28.018681], [-15.794088, 28.018681]]]
add_to_list(coordinates, 3)
#[[[-12.418887, 31.180395], [-12.418887, 31.180395]], [[-12.794088, 31.018681], [[-12.794088, 31.018681]]]]
# A more general case:
add_to_list([1, [2, [5, [6]]], 3], 2)
# [3, [4, [7, [8]]], 5]
# Degenerate cases
add_to_list([], 2)
# []
add_to_list(5, 2)
# 7
This assumes that your nested data will either be numbers or lists.
coordinates = [[[-15.418887, 28.180395], [-15.418887, 28.180395]],
[[-15.794088, 28.018681], [-15.794088, 28.018681]]]
def recursively_add3(l):
if isinstance(l, float):
return l
for index, inner_list in enumerate(l):
inner_result = recursively_add3(inner_list)
if inner_result is not None:
l[index] = inner_result + 3
return None
recursively_add3(coordinates)
which gives the result
[[[-12.418887, 31.180395], [-12.418887, 31.180395]]
, [[-12.794088, 31.018681], [-12.794088, 31.018681]]]
General map approach to apply a function only to the innermost elements of a randomly deeply nested list:
def map_nested(fnc, lst):
if not isinstance(lst, list):
return fnc(lst)
return [map_nested(fnc, x) for x in lst]
# or for in-place mutation:
# lst[:] = (map_nested(fnc, x) for x in lst)
# return lst
add3 = lambda x: x+3
map_nested(add3, coordinates)
# [[[-12.418887, 31.180395], [-12.418887, 31.180395]],
# [[-12.794088, 31.018681], [-12.794088, 31.018681]]]
You are using a 3D vector (lists of lists of lists) of coordinates right? Then your loop should be triple to access to all the variables on that 3D vector.
for x in list: #x is a list of lists
for y in x: #y is a list
for z in y: #z is a pair of coordinates
#Your code here
I have a data set which is a list of lists, looking like this:
[[-0.519418066, -0.680905835],
[0.895518429, -0.654813183],
[0.092350219, 0.135117023],
[-0.299403315, -0.568458405],....]
its shape is (9760,) and I am trying to remove all entries where the value of the first number in each entry is greater than 0, so in this example the 2nd and 3rd entries would be removed to leave
[[-0.519418066, -0.680905835],
[-0.299403315, -0.568458405],....]
So far I have written:
for x in range(9670):
for j in filterfinal[j][0]:
if filterfinal[j][0] > 0:
np.delete(filterfinal[j])
this returns: TypeError: list indices must be integers or slices, not list
Thanks in advance for any help on this problem!
You can use numpy's boolean indexing:
>>> x = np.random.randn(10).reshape((5,2))
array([[-0.46490993, 0.09064271],
[ 1.01982349, -0.46011639],
[-0.40474591, -1.91849573],
[-0.69098115, 0.19680831],
[ 2.00139248, -1.94348869]])
>>> x[x[:,0] > 0]
array([[ 1.01982349, -0.46011639],
[ 2.00139248, -1.94348869]])
Some explanation:
x[:,0] selects the first column of your array.
x > 0 will return an array of the same shape where each value is replaced by the result of the element-wise comparison (i.e., is the value > 0 or not?)
So, x[:,0] > 0 will give you an array of shape (n,1) with True or False values depending on the first value of your row.
You can then pass this array of booleans as an index to your original array, where it will return you an array of only the indexes that are True. By passing in a boolean array of shape (n,1), you select per row.
You are talking about "shape", so I assume that you are using numpy. Also, you are mentioning np in your example code, so you are able to apply element wise operations together with boolean indexing
array = np.array([[-0.519418066, -0.680905835],
[0.895518429, -0.654813183],
[0.092350219, 0.135117023],
[-0.299403315, -0.568458405]])
filtered = array[array[:, 0] < 0]
Use a list comprehension:
lol = [[-0.519418066, -0.680905835],[0.895518429, -0.654813183],[0.092350219, 0.135117023],[-0.299403315, -0.568458405]]
filtered_lol = [l for l in lol if l[0] <= 0]
You can use a list comprehension that unpacks the first item from each sub-list and retains only those with the first item <= 0 (assuming your list of lists is stored as variable l):
[l for a, _ in l if a <= 0]
You can go through this in a for loop and making a new list without the positives like so:
new_list = []
for item in old_list:
if item[0] < 0:
new_list.append(item)
But I'd prefer to instead use the in built filter function if you are comfortable with it and do something like:
def is_negative(number):
return number < 0
filtered_list = filter(is_negative, old_list)
This is similar to a list comprehension - or just using a for loop. However it returns a generator instead so you never have to hold two lists in memory making the code more efficient.
I would like to know how to extract sub_arrayes from an array(which can be in different sizes). Therefore, by given an array I want a sum of sub array elements like:
Array = [1, 2, 3]
SubArray = [(1),(2),(3),(1,2),(2,3),(1,2,3)]
My question is, how to create such a sub array for an array with different size and how to XOR subArray elements as a final result in python.
I don't want to use numpy!
You could use:
sublist = []
for i in range(1, len(mylist)+1): # number of items in sublist
for j in range(len(mylist)-i+1): # index of sublist
sublist.append( tuple(mylist[j:j+i]) )
For the second problem (xor-ing all elements), you can use:
result = 0
for sub in sublist:
for e in sub:
result ^= e
However, if you don't need sublist after this, you can just do:
sublist = []
for i in range(1, len(mylist)+1): # number of items in sublist
for j in range(len(mylist)-i+1): # index of sublist
for e in mylist[j:j+i]:
result ^= e
This removes some redundancy.
You can use something like this:
itertools.chain(*(itertools.combinations(Array, r=r) for r in range(1, len(Array)+1)))
I have the following 2D list
list = [[1,1,a],[2,2,b],[3,3,c]]
and I want to convert this 2D list to one 2D list and an array
sublist = [[1,1],[2,2],[3,3]]
subarray = [a,b,c]
Is there any convenient way to do that in python. I'm new to python, so I dont know if there's any grammar which can perform the above calculation.
Try this:
lst = [[1,1,a],[2,2,b],[1,3,c]]
sublist = list(map(lambda x: [x[0],x[1]], lst))
subarray = list(map(lambda x: x[2], lst))
List comprehensions are a good, clean solution:
sublist = [[a[0], a[1]] for a in list]
subarray = [a[2] for a in list]