簡體   English   中英

Python:搜索元組的排序列表

[英]Python: Search a sorted list of tuples

有用的信息:

有關如何對各種數據類型列表進行排序的信息,請參閱: 如何對列表/元組進行排序(列表/元組)?

..以及有關如何在排序列表上執行二進制搜索的信息,請參閱: Python中的二進制搜索(二分)

我的問題:

如何巧妙地將二進制搜索(或其他log(n)搜索算法)應用於某種數據類型的列表,其中鍵是數據類型本身的內部組件? 為了簡化問題,我們可以使用元組列表作為示例:

x = [("a", 1), ("b",2), ("c",3)]
binary_search(x, "b") # search for "b", should return 1
# note how we are NOT searching for ("b",2) yet we want ("b",2) returned anyways

為了進一步簡化:我們只需返回一個搜索結果,而不是多個,例如(“b”,2)和(“b”,3)都存在。

更好的是:

我們如何修改以下簡單代碼來執行上述操作?

from bisect import bisect_left

def binary_search(a, x, lo=0, hi=None):  # can't use a to specify default for hi
    hi = hi if hi is not None else len(a)  # hi defaults to len(a)   
    pos = bisect_left(a, x, lo, hi)  # find insertion position
    return (pos if pos != hi and a[pos] == x else -1)  # don't walk off the end

請注意 :我不是在尋找完整的算法本身。 相反,我正在尋找Python的一些標准(ish)庫的應用程序,和/或Python的其他功能,以便我可以隨時輕松搜索某些任意數據類型的排序列表。

謝謝

利用詞典排序如何處理不等長度的元組:

# bisect_right would also work
index = bisect.bisect_left(x, ('b',))

有時可以方便地將自定義序列類型提供給bisect

class KeyList(object):
    # bisect doesn't accept a key function, so we build the key into our sequence.
    def __init__(self, l, key):
        self.l = l
        self.key = key
    def __len__(self):
        return len(self.l)
    def __getitem__(self, index):
        return self.key(self.l[index])

import operator
# bisect_right would *not* work for this one.
index = bisect.bisect_left(KeyList(x, operator.itemgetter(0)), 'b')

將元組列表轉換為字典怎么樣?

>>> d = dict([("a", 1), ("b",2), ("c",3)])
>>> d['b'] # 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM