简体   繁体   English

在列表列表中查找最小的数字

[英]Find smallest number in list of lists

I have the following data set: 我有以下数据集:

data = 
{
a:[1,2,3]
b:[3,4,5]
c:[5,6,7]
...
}

And I am trying to find the smallest number from the index 1 from all the lists. 我正在尝试从所有列表的索引1中找到最小的数字。

The only way I could imagine doing it would be this: 我能想象的唯一方法是:

num = []
index_number = 1

for var in data:
  num.append(data.get(var)[index_number])
return min(num)

But i think this is not a very good solution. 但是我认为这不是一个很好的解决方案。

Also I will have to find the key that corresponds to the value that i just found. 另外,我还必须找到与我刚刚找到的值相对应的键。

Is there a good solution that i am not aware of? 有我不知道的好的解决方案吗?

data = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': [5, 6, 7]}
min_key = min(data,key=lambda key:min(data[key]))

this tells python you want the "min" value of the data dict, we will use the minimum of each keys list of values as our comparison key in finding the min 这告诉python您想要数据字典的“最小”值,我们将使用每个键值的最小值作为比较键来查找最小值

A simple comprehension may do the trick: 一个简单的理解就可以解决问题:

>>> data = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': [5, 6, 7]}
>>> index_number = 1
>>> min(((k, v[1]) for k, v in data.items()), key=lambda x: x[1])
('a', 2)

If you need only the minimum value, you may use a simpler approach 如果仅需要最小值,则可以使用更简单的方法

>>> data = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': [5, 6, 7]}
>>> index = 1
>>> min(v[index] for v in data.values())
2

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

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