搜索排序列表?

新手上路,请多包涵

搜索或操作排序 序列 的 Pythonic 方法是什么?

原文由 Basilevs 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 374
2 个回答

Python:

 import bisect

def find_in_sorted_list(elem, sorted_list):
    # https://docs.python.org/3/library/bisect.html
    'Locate the leftmost value exactly equal to x'
    i = bisect.bisect_left(sorted_list, elem)
    if i != len(sorted_list) and sorted_list[i] == elem:
        return i
    return -1

def in_sorted_list(elem, sorted_list):
    i = bisect.bisect_left(sorted_list, elem)
    return i != len(sorted_list) and sorted_list[i] == elem

L = ["aaa", "bcd", "hello", "world", "zzz"]
print(find_in_sorted_list("hello", L))  # 2
print(find_in_sorted_list("hellu", L))  # -1
print(in_sorted_list("hellu", L))       # False

原文由 Paulo A. Ferreira 发布,翻译遵循 CC BY-SA 4.0 许可协议

bisect 是标准库的一部分 - 这是您要找的东西吗?

原文由 Daniel Roseman 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题