从具有不同列表长度的列表中获取加权随机值

问题描述 投票:0回答:3

我需要创建一个新列表,该列表具有从列表列表中拉出的随机值,其中辅助列表的长度可能不同。

此外,例如,如果二级列表之一大于其余二级列表,则从所述列表中获取值的概率必须高于较短的二级列表的概率。随机值可以选择一次以上,这意味着我不必在选择后将其从列表中删除。

我能够创建列表列表,其中每个辅助列表都对应一个区域,其内容对应于随机生成的客户代码,到目前为止,效果很好。但是,当我使用random.choice()函数创建带有随机值的新列表时,我从可用列表中获得了x数量的随机列表,而不是从ALL列表中选取的随机值。

thislist = []

# So I have my blank list and I am ready to populate the list with, 
# in this case, 10 random values from the list of lists named 'codigo_cliente'

for i in range(10):
    thislist.append(random.choice(codigo_cliente))

此示例中的客户端代码共有30个客户端:

客户代码:

[['A-336', 'A-437', 'A-720', 'A-233', 'A-499'], 
 ['B-664', 'B-133', 'B-267', 'B-421', 'B-553', 'B-910', 'B-792', 'B-719', 'B-550', 'B-946'], 
 ['C-755', 'C-533', 'C-596', 'C-877', 'C-400', 'C-354', 'C-471', 'C-169', 'C-329', 'C-318', 'C-550', 'C-422', 'C-251', 'C-852', 'C-309']]

我得到以下输出,这不是我想要的:

这是所选客户的随机列表:

[['B-664', 'B-133', 'B-267', 'B-421', 'B-553', 'B-910', 'B-792', 'B-719', 'B-550', 'B-946'], 
 ['A-336', 'A-437', 'A-720', 'A-233', 'A-499'], 
 ['C-755', 'C-533', 'C-596', 'C-877', 'C-400', 'C-354', 'C-471', 'C-169', 'C-329', 'C-318', 'C-550', 'C-422', 'C-251', 'C-852', 'C-309'], 
 ['A-336', 'A-437', 'A-720', 'A-233', 'A-499'], 
 ['B-664', 'B-133', 'B-267', 'B-421', 'B-553', 'B-910', 'B-792', 'B-719', 'B-550', 'B-946'], 
 ['C-755', 'C-533', 'C-596', 'C-877', 'C-400', 'C-354', 'C-471', 'C-169', 'C-329', 'C-318', 'C-550', 'C-422', 'C-251', 'C-852', 'C-309'], 
 ['C-755', 'C-533', 'C-596', 'C-877', 'C-400', 'C-354', 'C-471', 'C-169', 'C-329', 'C-318', 'C-550', 'C-422', 'C-251', 'C-852', 'C-309'], 
 ['C-755', 'C-533', 'C-596', 'C-877', 'C-400', 'C-354', 'C-471', 'C-169', 'C-329', 'C-318', 'C-550', 'C-422', 'C-251', 'C-852', 'C-309'], 
 ['B-664', 'B-133', 'B-267', 'B-421', 'B-553', 'B-910', 'B-792', 'B-719', 'B-550', 'B-946'], 
 ['A-336', 'A-437', 'A-720', 'A-233', 'A-499']]

相反,我应该得到类似以下内容的东西:

thislist = ['A-336', 'B-553', 'C-596', 'B-910', 'C-251', 'C-329', 'B-910', 'A-437', 'B-946', 'C-251'] 

# Notice how there are more values with the "C" prefix from the larger secondary list,
# than values with the A or B prefixes from the smaller secondary lists.
python list random nested-lists
3个回答
1
投票

您不是从那些嵌套列表中选择随机项目,而是完整的嵌套列表。


1
投票

random.choices()weights参数设置为列表的长度一起使用。这将根据列表的长度选择列表。然后使用random.choice()从每个列表中选择一个元素。 k是要选择的项目数:


1
投票

加权选择的随机选择

© www.soinside.com 2019 - 2024. All rights reserved.