Minimum tuple search value

I have a list that contains a tuple, inside each tuple there is a list and a link value For example.

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 is the minimum in the list. Now the built-in min () function does not actually do this. She compares her based on the actual list, which is Mylist [i] [0]

I can only do this if the list contains two elements: But I did not understand how to do this in the list .. say 10 items!

 def min(a,x,b,y): t = a if x >= y: t = b return t 
+5
source share
5 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 .

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

+6
source

If you first save your list with a value, you can simply 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])

+2
source

my decision

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

returns a list of items with a minimum value

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

for example, if you have a list, for example

 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 do not know if you need this, but it works: D

+1
source

Just for fun, 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 a single-line key set to the min function is certainly more useful in a practical sense, I thought I would share it for educational purposes.

0
source

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)) 
-1
source

Source: https://habr.com/ru/post/1234125/


All Articles