0
How to process tuple in a list?
A list like [(1,a,2),(2,b,3)] is given and I have to process last find the smallest among the last element of the tuples. How can I do this?
5 Réponses
+ 4
Sorry Honfu, your solution gives an Error: "int object is not callable".
+ 4
If i understood it correctly, that the smallest 3rd element in tuples should be found:
(This not the shortest solution - I know)
lst = [(1,'a',2),(2,'b',3),(7,'c',11),(4,'d',2)]
min = lst[0][2]
for i in lst:
if i[2] < min:
min = i[2]
print(min)
# output is 2
+ 2
min(your_list, key=lambda x: x[2])
+ 2
Ah, okay, if not the tuple itself, but the number only is supposed to be found, just append a [2] to my min call.
Basically we get to the same result walking a different path:
You compare the last values directly, I compare the tuples by their last values.
+ 1
Lothar, I have just ran it to see if I was mistaken, but the code does what it's supposed to do:
Find the smallest tuple in a list by the last element.
Copypaste this and see for yourself:
a =[(4, 3, 2), (5, 7, 1), (3, 3, 3)]
print(min(a , key=lambda x: x[2]))
Output: (5, 7, 1), because this is the tuple with the smallest last element.