Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search min value within a list of tuples

I have a list which contain a tuple, within each tuple there's a list and a interger value E.g.

Mylist = [([1,1,3], 3),([1,1,3], 30),([2,2,3], 15),([1,3,3], 2)]

I want this list to return this tuple ([1,3,3], 2) since Mylist[i][1] = 2 that is the min in the list. Now, the built-in function min() doesn't really do that.. it compares it on the basis of the actual list that is Mylist[i][0]

I can perform this only if the list contains two items: But i have not figured how to do it in a list of.. say 10 items!

def min(a,x,b,y):
   t = a
   if x >= y:
       t = b
   return t
like image 919
user Avatar asked Oct 20 '15 13:10

user


3 Answers

Mylist = [([1,1,3], 3),([1,1,3], 30),([2,2,3], 15),([1,3,3], 2)]
print min(Mylist,key=lambda x:x[1])

You can provide a key to min function using lambda.

Output:([1, 3, 3], 2)

like image 140
vks Avatar answered Oct 22 '22 07:10

vks


If you store your list with the value first then you can just use min and sorted directly:

Mylist = [(3, [1,1,3]), (30, [1,1,3]), (15, [2,2,3]),(2, [1,3,3])]
min(Mylist)

Output: (2, [1, 3, 3])

like image 26
Barry Hurley Avatar answered Oct 22 '22 06:10

Barry Hurley


my solution

myList =  [([1, 1, 3], 3), ([1, 1, 3], 30), ([2, 2, 3], 15), ([1, 3, 3], 2)]
minValue = [i for i in myList if i[1] == min([x[1] for x in myList])]

return a list of items with the min value

[([1, 3, 3], 2)]

for example if you have a list like

myList =  [([1, 1, 3], 3), ([1, 1, 3], 30), ([2, 2, 3], 15), ([1, 3, 3], 2), ([1, 1, 3], 2)]

Result will be

[([1, 3, 3], 2),([1, 1, 3], 2)]

I don't know if you need this but works :D

like image 32
efirvida Avatar answered Oct 22 '22 08:10

efirvida