Finding the minimum and maximum of a list of arrays - python

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]]

Related

Extract indices of certain values from a list in python

Suppose, I have a list [0.5,1,1.5,2,2.5,3,3.5,4,4.5], now I would like to extract the indices of a list [1.5,2.5,3.5,4.5], which is a subset of that list.
You can use the inbuilt function <list>.index to find the index of each element(of second list) in the first list.
Having that learnt, you can use list comprehension to achieve what you want:
>>> list1 = [0.5,1,1.5,2,2.5,3,3.5,4,4.5]
>>> list2 = [1.5,2.5,3.5,4.5]
>>> [list1.index(elem) for elem in list2]
[2, 4, 6, 8]
One other option is to use enumerate function. See the following answer:
a = [0.5,1,1.5,2,2.5,3,3.5,4,4.5]
b = [1.5,2.5,3.5,4.5]
indexes = []
for id, i in enumerate(a):
if i in b:
indexes.append(id)
print(indexes)
The output is going to be [2, 4, 6, 8].

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]]

How to sum arrays within an array?

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

multiple assignments in one line for loop python

I would like a one line way of assigning two variables to two different values in a for loop.
I have a list of list of values
list_values = [[1, 2, 3], [4, 5, 6]]
I have tried to do this, and it works but is not pythony:
first = [i[0] for i in list_values]
second = [i[1] for i in list_values]
Which makes:
first = [1, 4]
second = [2, 5]
I want to write something like:
first, second = [i[0]; i[1] for i in list_values]
Is something like this possible?
You could use the zip() function instead:
first, second = zip(*list_values)[:2]
or the Python 3 equivalent:
from itertools import islice
first, second = islice(zip(*list_values), 2)
zip() pairs up elements from the input lists into a sequence of new tuples; you only need the first two, so you slice the result.
list_values = [[1, 2, 3], [4, 5, 6]]
first, second = [[i[0], i[1]] for i in list_values]
Next time use something other than the "i", like "elem" etc.

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