简体   繁体   中英

find minimum value in list of strings and numbers python

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM