1

In dictionary where keys are numbers, how to find key which is smaller then a given number but the most near to given number ?

I can sort list of keys in ascending and then while but is there more python way to do this ( I am from Java and this is Java approach)

example:
{{1:9}, {6:7}, {5:45}, {3:90}}
for given number 4 result is 3
4

1 回答 1

10

我认为 Vicktor Kerkez 的回应的变体是最清楚的:

d = {1:9, 6:7, 5:45, 3:90}
print max(k for k in d if k < 4)

k for k in d if k < 4部分遍历键并仅返回小于 4 的键。然后max()返回其中最大的键。

于 2013-09-16T23:49:16.500 回答