How to sum arrays within an array? - python

Basically i have array = [[1 2 3],[4 5 6]]
I want to sum the values within 1 array to get sum_array = [6,15].
I have tried sum(array) on my actual dataset and got random numbers.(not the anticipated output).

sum can only be performed on an element that is configured with __add__ to handle it. For a list it needs to be, in a loose sense single dimensioned. Hence you need to get the flattened list inside.
Using List comprehension.
>>> [sum(l) for l in array]
=> [6, 15]
Using map
>>> list( map(sum, array) )
=> [6, 15]
#driver values :
IN : array = [[1,2,3],[4,5,6]]

Apart from existing answers, you can also use map and sum together for a better and cleaner approach:
array = [[1, 2, 3],[4, 5, 6]]
sumArray = map(sum, array)
OUTPUT
>>> sumArray
[6, 15]

You can use sum(array) as you suggested, just make sure you're creating a list with the values returned by sum:
array = [[1, 2, 3], [4, 5, 6]]
sums = [sum(x) for x in array]
>> [6, 15]

Using list comprehension along with sum eases the above task.
a = [ [1,2,3] , [4,5,6] ]
sum_list = [ sum[elem] for elem in a ]
print(sum_list)
#Output [6,15]
The below approach is lengthy, but I feel it is easier to understand for the beginner
array = [ [1,2,3], [4,5,6] ]
sum_list = []
for elements in array:
elements_sum = 0
for elem in elements:
elements_sum = elements_sum + elem
sum_list.append(elements_sum)
print(sum_list)
#Output [6,15]

and if you want the full sum of the array of array
do that
print(sum(list(map(sum, array)))
this will give you 21

Related

How to create dynamic multidimensional list in python

I know there are a lot of questions like this one, but I haven't found my answer so far.
I am trying to dynamically fill a list with other lists, but I don't know why my code doesn't do what I want.
My code:
x = [1,2,3]
y = [4,5,6]
x.append(y)
print (x)
What I get:
[1,2,3[4,5,6]]
What I realy want:
[[1,2,3],[4,5,6]]
My goal would be, to dynamically add more dimensions arranged like this.
Can somebody tell me, what I'm doing wrong?
Thanks a lot.
In your example, x is a list containing three elements (integers).
With append, you add a new element. By appending y, you are adding a list as a fourth element (3 integers, one list).
If you want to create a list of lists, tread x and y as elements for that, and combine them in a list:
x = [1,2,3]
y = [4,5,6]
list_of_lists = [x,y]
list_of_lists will then be [[1, 2, 3], [4, 5, 6]].
You can add another list by appending them:
list_of_lists.append([7,8,9])
... which will result in list_of_lists being [[1, 2, 3], [4, 5, 6], [7, 8, 9]].
What you want is create a list of lists. You can do:
x = [1,2,3]
y = [4,5,6]
l = [x,y]
print(l)
Actually, if you want to deal with multi-dimensional arrays, you should probably look at the numpy library (https://numpy.org/)
x = [1,2,3]
y=[22,33,9]
x=(x,y)
print (list(x))
>> [[1, 2, 3], [22, 33, 9]]
x=list(x) #Perform type conversion of the output 'x' to get in list type
x.append([13,32,12])#then append the data you want
print (x)
>> [[1, 2, 3], [22, 33, 9], [13, 32, 12]]

outcome first list in 2 dimensional list

I have a 2 Dimensional list like that :
list = [[2, 3, 5], [1,2,3], [4,5,6], [8,9,10],[5,6,7]]
I can print the first value of every list with this:
[i[0] for i in list]
and outcome is:
list = [2, 1, 4, 8, 5]
but i want to have outcome like this :
list = [[2,3,5],[1,2,3],[4,5,6]]
my code is this :
new_list = []
for i in list:
row = 1
row_list = list[row]
new_list.append(row_list)
can anyone help me?
I am a bit confused what are you asking, but if I get i right try
print(list[1][1]) #print 2nd element in 2nd subset
print(list[0:3]) #print first 3 elements (in this case subsets) in the list
I hope it help.
To remove few object from list, you can use
list.remove(something) #remove element from list
or to create new list just use
l=list[0:3]
but i want to have outcome like this : list = [[2,3,5],[1,2,3],[4,5,6]]
This should do it:
list_subset = list[:3] # the first 3 elements in the list
you can slice your list like this:
n = 3 # if you have number of items you need
new_list = list[:n]
or:
n = 2 # if you have number of items you want to remove
new_list = list[:-n]
note that:
DO NOT use list as a name of a variable, list is a built-in in python.
Simple slicing can be used to skip last two rows like this:
list = [[2, 3, 5], [1,2,3], [4,5,6], [8,9,10],[5,6,7]]
print(list[:-2])
[[2, 3, 5], [1, 2, 3], [4, 5, 6]]

Sum of all numbers in the first or second place in an array

I have a 2d list, for example:
list1 = [[1,2],[3,4],[5,6],[7,8]]
and I want to find the sum of all the numbers at the n'th place of every element.
For example if I want the answer for 0, I would calculate:
my_sum = list1[0][0] + list1[1][0] + list1[2][0]
or
my_sum = 0
place = 0
for i in range(len(list1)):
my_sum += list1[i][place]
return my_sum
Output: 16
Is there a more elegant way to do this? Or one that uses only one line of code?
I mean as fictional code for example:
fictional_function(list1,place) = 16
Since you are looking for a functional solution, consider operator.itemgetter:
from operator import itemgetter
L = [[1,2],[3,4],[5,6],[7,8]]
res = sum(map(itemgetter(0), L)) # 16
For performance and simpler syntax, you can use a 3rd party library such as NumPy:
import numpy as np
A = np.array([[1,2],[3,4],[5,6],[7,8]])
res = A[:, 0].sum() # 16
As a generalization if you want multiple indices (e.g. 0 and 1) you could use reduce combined with and element-wise sum something like this:
from functools import reduce
def fictional_function(lst, *places):
s_places = set(places)
def s(xs, ys):
return [x + y for x, y in zip(xs, ys)]
return [x for i, x in enumerate(reduce(s, lst)) if i in s_places]
list1 = [[1, 2], [3, 4], [5, 6], [7, 8]]
print(fictional_function(list1, 0))
print(fictional_function(list1, 0, 1))
print(fictional_function(list1, *[1, 0]))
Output
[16]
[16, 20]
[16, 20]
The idea is that the function s sums two list element-wise, for example:
s([1, 2], [3, 4]) # [4, 6]
and with reduce apply s to a list of lists, finally filter the result for the intended indices (places) only.
list1 = [[1,2],[3,4],[5,6],[7,8]]
ind = 0
sum_ind = sum(list(zip(*list1))[ind])
The above can be even written as function taking list and the index as input and returns the sum of the common index.
What we do in the above is first we get all the same indexes to individual lists using zip and then chooses which index one has to be summed and passes the same to sum function.

Finding the minimum and maximum of a list of arrays

Let's say I have 2 arrays inside a single array, like:
main_array = [[1, 2, 3, 4], [4, 5, 6, 7]]
I would like to find the min and max of each of those arrays and store them in a single array. For the above it would be:
result = [1, 4, 4, 7]
How do I use Python's inbuilt min() and max() in this case?
I tried min(main_array) and max(main_array) but that is giving me:
result = [1,7]
You can just use min() or max() on single list to get it's min/max value. You can also use list comprehension to loop through lists in list and functions you want to use:
main_array = [[1,2,3,4], [4,5,6,7]]
res = [func(l) for l in main_array for func in (min, max)]
print(res)
main_array = [[1, 2, 3, 4], [4, 5, 6, 7]]
result = []
for inner_list in main_array:
result.append(min(inner_list))
result.append(max(inner_list))
Probably the more readable way to do it is:
result = []
for list in main_array:
result.append(min(list))
result.append(max(list))
print(result)
Try
main_array = [[1,2,3,4],[4,5,6,7]]
out = []
for arr in main_array:
out.extend([min(arr), max(arr)])
print(out)
You need to iterate over each of the sub arrays and call min and max on that.
You could also use generators
def minthenmax(arr):
for i in arr:
yield min(i)
yield max(i)
print(list(minthenmax(main_array)))
First off you're missing a common on the definition of your main array...
main_array = [[1,2,3,4],[4,5,6,7]]
To get the min of the first sub-array.
min(main_array[0])
...and the max...
max(main_array[0])
Hopefully you can work out the rest from this.
In one line. You can use build-in map function to map two inner lists to min function and then max function. Finally you can concatenate them.
map(min, main_array) + map(max, main_array)
main_array = [[1,2,3,4],[4,5,6,7]]
x = min(main_array[0]), max(main_array[0])
y = min(main_array[1]), max(main_array[1])
new_array = [i for i in x + y]
print (new_array)
output:
[1, 4, 4, 7]
You've got to search for min and max on each item of lst.
lst = [[1,2,3,4],[4,5,6,7]]
m = []
for k in lst: m.append([min(k), max(k)])
=> [[1, 4], [4, 7]]

Search in 2D list using python to find x,y position

I have 2D list and I need to search for the index of an element. As I am begineer to programming I used the following function:
def in_list(c):
for i in xrange(0,no_classes):
if c in classes[i]:
return i;
return -1
Here classes is a 2D list and no_classes denotes the number of classes i.e the 1st dimesntion of the list. -1 is returned when c is not in the araray. Is there any I can optimize the search?
You don't need to define no_classes yourself. Use enumerate():
def in_list(c, classes):
for i, sublist in enumerate(classes):
if c in sublist:
return i
return -1
Use list.index(item)
a = [[1,2],[3,4,5]]
def in_list(item,L):
for i in L:
if item in i:
return L.index(i)
return -1
print in_list(3,a)
# prints 1
if order doesn't matter and you have no duplicates in your data, I suggest to turn you 2D list into list of sets:
>>> l = [[1, 2, 4], [6, 7, 8], [9, 5, 10]]
>>> l = [set(x) for x in l]
>>> l
[set([1, 2, 4]), set([8, 6, 7]), set([9, 10, 5])]
After that, your original function will work faster, because search of element in set is constant (while search of element in list is linear), so you algorithm becomes O(N) and not O(N^2).
Note that you should not do this in your function or it would be converted each time function is called.
If your "2D" list is rectangular (same number of columns for each line), you should convert it to a numpy.ndarray and use numpy functionalities to do the search. For an array of integers, you can use == for comparison. For an array of float numbers, you should use np.isclose instead:
a = np.array(c, dtype=int)
i,j = np.where(a == element)
or
a = np.array(c, dtype=float)
i,j = np.where(np.isclose(a, element))
such that i and j contain the line and column indices, respectively.
Example:
a = np.array([[1, 2],
[3, 4],
[2, 6]], dtype=float)
i, j = np.where(np.isclose(a, 2))
print(i)
#array([0, 2])
print(j)
#array([1, 0]))
using list comprehension: (2D list to 1D)
a = [[1,22],[333,55555,6666666]]
d1 = [x for b in a for x in b]
print(d1)

Categories

Resources