[英]Find smallest number in nested lists at the same index
I have a list of products:我有一个产品清单:
list = [['product 1', 2.4, 322], ['product 2', 5.35, 124], ['product 3', 8.41, 521]]
How can I loop through the list to find the product with lowest number at the index [1]?如何遍历列表以查找索引 [1] 中编号最小的产品?
You can use a key
for min
:您可以为
min
使用key
:
min(data, key=lambda p: p[1])
product = min(list, key=lambda item: item[1])[2]
Do not use list
as a variable name, since list
already refers to a list constructor.不要使用
list
作为变量名,因为list
已经引用了一个列表构造函数。
You can use an external variable.您可以使用外部变量。 And if any value is less than that you simply replace the array.
如果任何值小于该值,您只需替换数组。
data = [['product 1', 2.4, 322], ['product 2', 5.35, 124], ['product 3', 8.41, 521]]
min_arr = data[0]
for arr in data:
min_arr = arr if arr[1] < min_arr[1] else min_arr
print(min_arr)
#Output
['product 1', 2.4, 322]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.