Given the following list:
f = [[1, 19], [1, 19], [1, 19], [2, 18], [16, 4], [10, 10]]
I want to get the smallest value of each sub-list and create:
f1 = [1, 1, 1, 2, 4, 10]
How can I do this?
Using min() Method to find smallest number in a list.
Use Python's min() and max() to find smallest and largest values in your data.
How to calculate the minimum of a list of numbers? To find the smallest value (the minimum) among a list of numbers, it is necessary to go through the whole list of numbers and compare their values one after the other. The minimum in the list is the smallest value found when all values have been compared.
Process: Initially assign the element located at 0 to min using min = l[0]. using for loop visit each location serially from 1 to len(l)-1. if the element located in any position is lesser than min, then assign the element as min by using min = l[i] finally min holds the minimum value in the list.
In plain Python, this implementation looks like the following: Now there is a built-in function for finding the largest and the smallest element in a list in a single line. You don’t need to do any additional imports, or anything else. Just call the max or the min function with the list and you are basically done:
Given a list of numbers, the task is to write a Python program to find the smallest number in given list. Method 1 : Sort the list in ascending order and print the first element in the list. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
Given M sorted lists of variable length, efficiently compute the smallest range, including at least one element from each list. We can solve this problem in O (N.log (M)) time using a min-heap where N is the total number of elements present in M lists.
The result of the min () method seems a bit strange, since according to the alphabet “alex” should be the smallest element. The “natural order” for strings is the order of the Unicode codes, according to which the uppercase letters come before the lowercase letters. That’s why in this case “Bob” is the smallest element.
Since it's a Python list, you can use min
function for each sub-list using list-comprehension
[min(subList) for subList in f]
OUTPUT:
[1, 1, 1, 2, 4, 10]
Or, you can even combine min
and map
together
list(map(min,f))
An easy numpy
way would be to use axis=1
with np.min
:
>>> f1 = np.min(f, axis =1)
>>> f1
array([ 1, 1, 1, 2, 4, 10])
A non-numpy
way could be to map min
to f
:
>>> list(map(min, f))
[1, 1, 1, 2, 4, 10]
you can use builtin min function
f = [[1, 19], [1, 19], [1, 19], [2, 18], [16, 4], [10, 10]]
f1 = []
for i in f:
f1.append(min(i))
f1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With