How can I return the first element of in a list of tuples by finding the smallest postive number in the second element?
e.g
a_list = [(0,6),(1,2),(2,-2),(3,-5)]
to return 1?
CodePudding user response:
You can do this by splitting your original list into two and then determining the smallest positive value in the second list. You can then print the index by passing it your smallest value, or use square bracket notation on your original list to return the tuple itself.
#Create the list
a_list = [(0,6),(1,2),(2,-2),(3,-5)]
#Split the tuple into two lists
first_element = [i[0] for i in a_list]
second_element = [i[1] for i in a_list]
#Find the smallest positive
smallest = min([i for i in second_element if i > 0])
#Return the index
where_in_list = second_element.index(smallest)
#Method 1
print(where_in_list)
#Method 2
a_list[where_in_list]
Output is 1 for Method 1 and (1, 2) for Method 2.
CodePudding user response:
You can assign the second element to another variable
eg.
a_list = [(0,6),(1,2),(2,-2),(3,-5)]
tuple = a_list[1] #as the counting goes 0,1,2....
if tuple[0]>tuple[1]:
greater_no = tuple[0]
else:
greater_no = tuple[1]
Hopefully it works, sorry I haven't tested it but this is my guess