3

キーとしてフロート、値としてオブジェクトを使用したdictがあります。フロートを受け取りましたが、このフロートが2つのキーの間にあることを知りたいのですが。どうすればこれを見つけることができますか?

コードでの意味の例:

a = {}
a[1.2] = some_unimportant_instance
a[2.3] = some_other_unimportant_instance
a[2.6] = some_third_unimportant_instance
etc...

r = 2.5
# a[r] will not work
# I want something that returns the two numbers around r
# in this case, 2.3 and 2.6.
4

3 に答える 3

7

最初の観察:dict-sはこれに悪いです。それらはハッシュを使用して実装され、完全に一致する場合にのみ値を取得するのに効率的です。あなたの目的のために、あなたは最初にdictをキーのリストに変換しなければならないでしょう。次に、bisectなどのモジュールを使用できます。

例:

import bisect
keys = sorted(a.keys())
index = bisect.bisect(keys, r)
if index >= 1:
    print keys[index - 1]
print keys[index]

更新:MarkDickinsonによって提案されたようにコードが改善されました。ありがとう!

于 2012-04-13T11:58:00.880 に答える
4

PyPIを使用するのはPythonicです。キーをソートされた順序で維持し、必要な二等分とインデックス付けをサポートするMutableMappingタイプがいくつかあります。まさにこの目的のために、 SortedDictタイプを持つsortedcontainersモジュールについて考えてみます。

from sortedcontainers import SortedDict
sd = SortedDict((key, value) for key, value in data)

# Get the would-be index of the desired key.
index = sd.bisect(2.5)

# Get the actual key at that index.
key = sd.iloc[index]

# Look ahead one to find the range.
ahead = sd.iloc[index + 1]

また、sortedcontainersは純粋なPythonであり、2.6から3.4と互換性があり、100%のテストカバレッジと何時間ものストレスがあり、ベンチマーク比較により、非常に高速であることが示されています(C実装として高速)。

于 2014-04-10T19:19:55.773 に答える
0

実際に2つのキーを返すには、次のことを考慮してください。

def surrounding_keys(needle, haystack):
    if haystack: # ensure it's not empty
        keys = sorted(haystack.keys())
        for (lower, upper) in zip(keys, keys [1:]):
            if lower < needle < upper:
                return (lower, upper)
    raise KeyError # fails with key error if: not found, empty dict, dict with only one key
于 2012-04-13T17:13:23.367 に答える