ฉันต้องการเขียน random.choice แบบถ่วงน้ำหนัก (แต่ละองค์ประกอบในรายการมีความน่าจะเป็นที่แตกต่างกันสำหรับการเลือก) นี่คือสิ่งที่ฉันมาด้วย:
def weightedChoice(choices):
    """Like random.choice, but each element can have a different chance of
    being selected.
    choices can be any iterable containing iterables with two items each.
    Technically, they can have more than two items, the rest will just be
    ignored.  The first item is the thing being chosen, the second item is
    its weight.  The weights can be any numeric values, what matters is the
    relative differences between them.
    """
    space = {}
    current = 0
    for choice, weight in choices:
        if weight > 0:
            space[current] = choice
            current += weight
    rand = random.uniform(0, current)
    for key in sorted(space.keys() + [current]):
        if rand < key:
            return choice
        choice = space[key]
    return Noneฟังก์ชั่นนี้ดูซับซ้อนเกินไปสำหรับฉันและน่าเกลียด ฉันหวังว่าทุกคนที่นี่สามารถให้คำแนะนำในการปรับปรุงหรือวิธีการอื่นในการทำเช่นนี้ ประสิทธิภาพไม่ได้สำคัญเท่ากับฉันในเรื่องความสะอาดและการอ่านรหัส
random.choicesการโทรแต่ละครั้งnumber_of_items_to_pickหากคุณต้องการมากของผลการสุ่มมันเป็นสิ่งสำคัญมากที่จะเลือกพวกเขาทั้งหมดในครั้งเดียวโดยการปรับ ถ้าคุณทำเช่นนั้นมันเป็นลำดับความสำคัญเร็วขึ้น