如何最好地显示随机字符串,其中一些字符串的权重比其他字符串重

How to best diplay a random string, with some strings weighted heavier than others

我正在尝试显示一个随机字符串,但希望某些字符串比其他字符串出现得更频繁。我目前的策略是使用嵌套字典以便于更新和 'choices' 函数。

msg_list = {

    'msg_1': {
        'msg': 'Hi',
        'weight': 40,
         },

    'msg_2': {
        'msg': 'hello',
        'weight': 50,
         },

    'msg_3': {
        'msg': "What's up",
        'weight': 10,
        },
    }

message = choices(msg_list['msg'], msg_list['weight'])
string = message['msg']

这显然行不通,我想我可以用一个循环来构建列表,但我很好奇是否有更快的方法来做到这一点。谢谢!

你快到了。 您只需要为 random.choices.

的 2 个参数创建列表
msg_list = {

    'msg_1': {
        'msg': 'Hi',
        'weight': 40,
        },

    'msg_2': {
        'msg': 'hello',
        'weight': 50,
        },

    'msg_3': {
        'msg': "What's up",
        'weight': 10,
        },
    }

weights = [msg_list[key]['weight'] for key in msg_list.keys()]
messages = [msg_list[key]['msg'] for key in msg_list.keys()]


message = choices(messages, weights)
string = message[0]