简体   繁体   English

在字符串和数字列表中找到最小值python

[英]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 我想抓住最小路径,在这种情况下是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() : 你可以使用min()key参数:

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. 函数operator.itemgetter(-1)返回每个列表的最后一个元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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