python瀛︿範--bisect妯″潡

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python瀛︿範--bisect妯″潡相关的知识,希望对你有一定的参考价值。

鏍囩锛?a href='http://www.mamicode.com/so/1/%e8%bf%94%e5%9b%9e' title='杩斿洖'>杩斿洖   res   鑰冭瘯鎴愮哗   print   strong   pytho   img   bis   鏍囧噯   

1. 妯″潡浠嬬粛

1. bisect妯″潡涓哄唴缃爣鍑嗗簱锛屽畠瀹炵幇浜嗕簩鍒嗘硶鏌ユ壘绠楁硶(鍙鎻愬埌浜屽垎娉曟煡鎵撅紝搴旇浼樺厛鎯冲埌姝ゆā鍧?/strong>)

2. 涓昏鍖呭惈鏈変袱涓嚱鏁帮細bisect鍑芥暟(鏌ユ壘鍏冪礌)鍜宨nsort鍑芥暟(鎻掑叆鍏冪礌)銆?/p>

2. 甯哥敤鏂规硶浠嬬粛

鍦烘櫙1锛氬凡鐭ヤ竴涓湁搴忓垪琛紝鏌ユ壘鐩爣鍏冪礌鐨勪綅缃储寮?/p>

鎶€鏈浘鐗? src=
import bisect

# 宸茬煡涓€涓湁搴忓簭鍒?/span>
ordered_list = [23, 34, 59, 78, 99]

des_element = 21
res = bisect.bisect(ordered_list, des_element)
print(res)  # res: 0

des_element = 35
res = bisect.bisect(ordered_list, des_element)
print(res)  # res: 2
View Code

璇存槑锛歜isect鍑芥暟浼氶粯璁よ繑鍥炲彸渚х殑浣嶇疆绱㈠紩锛屽悓鏃禸isect鍑芥暟鏄痓isect_right鍑芥暟鐨勫埆鍚嶃€?/p>

 

鍦烘櫙2锛氬凡鐭ヤ竴涓湁搴忓垪琛紝鍏朵腑鍒楄〃涓湁閲嶅鍏冪礌锛屾煡鎵剧洰鏍囧厓绱犵殑浣嶇疆绱㈠紩

鎶€鏈浘鐗? src=
import bisect

# 宸茬煡涓€涓湁搴忓簭鍒?/span>
ordered_list = [23, 34, 34, 59, 78, 99]

# bisect鍑芥暟榛樿杩斿洖鍙充晶鐨勪綅缃储寮?/span>
des_element = 34
res = bisect.bisect(ordered_list, des_element)
print(res)  # res: 3

# bisect鍑芥暟涓篵isect_right鍑芥暟鐨勫埆鍚?/span>
des_element = 34
res = bisect.bisect_right(ordered_list, des_element)
print(res)  # res: 3

# bisect_left鍑芥暟榛樿杩斿洖宸︿晶鐨勪綅缃储寮?/span>
des_element = 34
res = bisect.bisect_left(ordered_list, des_element)
print(res)  # res: 1
View Code

璇存槑锛氬鏋滅洰鏍囧厓绱犱細鍦ㄥ凡鐭ユ湁搴忓垪琛ㄤ腑澶氭鍑虹幇锛岄偅涔堢洰鏍囧厓绱犱粠宸茬煡鏈夊簭鍒楄〃鐨勫乏渚ф垨鍙充晶鎻掑叆鏃剁粨鏋滄槸涓嶅悓鐨勩€?/p>

3. 鍦烘櫙搴旂敤

鍦烘櫙1锛氭浛浠f-elif璇彞锛屼緥濡傦細鍒ゆ柇鑰冪敓鎴愮哗鎵€灞炵殑绛夌骇闂銆?/p>

鎶€鏈浘鐗? src=
鈥樷€樷€?/span>
    鑰冭瘯鎴愮哗鐨勬。浣嶅垝鍒嗭紝鍏卞垎涓?涓瓑绾э細
        1. F绛夌骇锛歔0, 60)
        2. D绛夌骇锛歔60, 70)
        3. C绛夌骇锛歔70, 80)
        4. B绛夌骇锛歔80, 90)
        5. A绛夌骇锛歔90, 100]
鈥樷€樷€?/span>

import bisect


def get_result(score: (int, float), score_nodes: list = [60, 70, 80, 90], ranks=鈥?/span>FDCBA鈥?/span>) -> str:

    # 鏍¢獙锛氬垎鏁拌寖鍥?/span>
    if score < 0 or score >100:
        return "score鐨勫彇鍊艰寖鍥达細0-100"

    # 杈圭晫鐐硅€冭檻
    if int(score) == 100:
        return "A"

    loc_index = bisect.bisect(score_nodes, score)
    return ranks[loc_index]

print(get_result(50))       # res: F
print(get_result(60))       # res: D
print(get_result(85.5))     # res: B
print(get_result(100))      # res: A
View Code

 

以上是关于python瀛︿範--bisect妯″潡的主要内容,如果未能解决你的问题,请参考以下文章

python瀛︿範鍩虹涓€

python瀛︿範绡?5 - 瀛楀吀 闆嗗悎

Python瀛︿範涔嬭矾鈥?018/7/11

Python-鍩轰簬socket鍜宻elect妯″潡瀹炵幇IO澶氳矾澶嶇敤

cmd鍛戒护鏌ョ湅Python妯″潡鍑芥暟绛夊府鍔╂枃妗e拰浠嬬粛

Python瀛︿範涔嬭緭鍏ュ拰杈撳嚭