Reputation: 33
I have the ouput
[['a', 'b', 'a', 'c', 'd', 20.0], ['a', 'b', 'd', 11.0], ['a', 'c', 'd', 10.0]]
and I want to grab the minimum path which in this case would be 10
it's a path finding algorithm and the letters can vary
i tried using a key of float but couldn't figure it out
Upvotes: 1
Views: 2059
Reputation: 602155
You can use the key
argument to min()
:
path = min(my_list, key=operator.itemgetter(-1))
This will apply the key function to each element of the list, and return the element for which the result of applying that funciton is minimal. The function operator.itemgetter(-1)
returns the last element of each list.
That said, you might reconsider your data structure. The hybride lists that contain names and then a floating point number as last element seem cumbersome to work with. Using a list of tuples with two entries might make your code more natural, in spite of adding one nesting level:
[(['a', 'b', 'a', 'c', 'd'], 20.0),
(['a', 'b', 'd'], 11.0),
(['a', 'c', 'd'], 10.0)]
Upvotes: 3