简体   繁体   English

在 python 中设置最小的第三个值

[英]Get set with smallest 3rd value in python

I have an array.我有一个数组。 This iterator-object including multiple tuples of length 3. I would like to pick a tuple with the smallest third value.这个迭代器对象包括多个长度为 3 的元组。我想选择一个第三个值最小的元组。

for example (I just wrote it down as a list but it's not a list)例如(我只是把它写成一个列表,但它不是一个列表)

a = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]

the output should be: output 应该是:

(1, 9, 0.3)

Use min with a custom key fetching the 3rd valuemin与获取第三个值的自定义键一起使用

values = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]

min_tuple = min(values, key=lambda x: x[2])
print(min_tuple)  # (1, 9, 0.3)

you can do an algorithm with linear complexity that will iterate in the in the array and find the smallest using the min function你可以做一个具有线性复杂度的算法,它将在数组中迭代并使用min function 找到最小的

and convert into tuple并转换成元组

Code:代码:

def smallest(a):
    result = []
    for x in a:
        result.append(min(x))
    return result
a=[(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)]
print(smallest(a)) #(1, 9, 0.3)
import functools a = [(1, 5, 4), (2, 5, 0.4), (3, 4, 0.4), (1, 9, 0.3)] print(functools.reduce(lambda c, m: m if m[2] < c[2] else c, a))

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

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