user
user

Reputation: 159

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

Upvotes: 5

Views: 3953

Answers (5)

Karthik
Karthik

Reputation: 11

Time Complexity = n

Mylist = [([1,1,3], 3),([1,1,3], 30),([2,2,3], 15),([1,3,3], 2)]
minv=MyList[0][1]
minv1=MyList[0][0]
for lst in MyList:
    if(lst[1]<minv):
        minv=lst[1]
        minv1=lst[0]
print(tuple(minv1,minv))

Upvotes: -1

efirvida
efirvida

Reputation: 4865

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

Upvotes: 1

Andrew Winterbotham
Andrew Winterbotham

Reputation: 1010

Just for interest's sake, here's a functional approach:

def get_min_tuple(l):
    def get_index(lst, num, index=0):
        if num in lst[index]:
            return index
        else:
            return get_index(lst, num, index + 1)
    def find_min(l, smallest=None, assigned=False):
        if l == []:
            return smallest
        else:
            if not assigned:
                smallest = l[0][1]
                assigned = True
            else:
                if l[0][1] < smallest:
                    smallest = l[0][1]
            return find_min(l[1:], smallest, assigned)
    return l[get_index(l, find_min(l))]

While the one-liner of supplying a key to the min function is of course more useful in a practical sense, I thought I'd share this for educational purposes.

Upvotes: 0

Barry Hurley
Barry Hurley

Reputation: 577

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

Upvotes: 2

vks
vks

Reputation: 67978

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)

Upvotes: 7

Related Questions