简体   繁体   中英

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.

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

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

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