Python: smallest number in list
Question:
I’m new to python and i don’t know how to find the smallest number in each array. The input is [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
and the output should be [2, 3, 5, 1]
. I have try this:
x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
minimal = x[0]
for i in range(len(x)):
if (x[i]< minimal):
minimal = x[i]
print(minimal)
And the output that i got is [2]
, i have no idea about this. Please help me…
Answers:
try this :
list(map(lambda x:min(x),[[2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]))
We can simply iterate through the nested list and append the minimum values for each of the list item.
smallest = []
for listItem in x:
smallest.append(min(listItem))
Now, smallest
list should be the expected output list.
First, we need to get individual lists from list x
using for lst in x:
. Then we find the minimum value of that list using min()
function & append it to your minimal
list using minimal.append(min(lst))
, then print the final minimal list
Now you will have your output as [2, 3, 5, 1]
Now try & understand this code:
x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
minimal = []
for lst in x:
minimal.append(min(lst))
print(minimal)
I’m new to python and i don’t know how to find the smallest number in each array. The input is [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
and the output should be [2, 3, 5, 1]
. I have try this:
x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
minimal = x[0]
for i in range(len(x)):
if (x[i]< minimal):
minimal = x[i]
print(minimal)
And the output that i got is [2]
, i have no idea about this. Please help me…
try this :
list(map(lambda x:min(x),[[2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]))
We can simply iterate through the nested list and append the minimum values for each of the list item.
smallest = []
for listItem in x:
smallest.append(min(listItem))
Now, smallest
list should be the expected output list.
First, we need to get individual lists from list x
using for lst in x:
. Then we find the minimum value of that list using min()
function & append it to your minimal
list using minimal.append(min(lst))
, then print the final minimal list
Now you will have your output as [2, 3, 5, 1]
Now try & understand this code:
x = [ [2], [3, 4], [6, 5, 7], [4, 1, 8, 3] ]
minimal = []
for lst in x:
minimal.append(min(lst))
print(minimal)