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 许可协议
Python: