从多个不同长度的列表中获取随机整数的更有效,更通用的方法

时间:2019-12-25 02:39:47

标签: python random

我想要的是能够具有可变长度的可变列表,并从这些列表中提取一个随机数。诀窍是这些列表的大小不同,因此,如果一个列表比其他列表小,则该列表中的数字不应像其他较大列表中那样频繁出现。

这就是我现在拥有的:

 import random

 a = 1
 b = 11
 c = 111
 d = 1111
 e = 11111
 f = 111111
 g = f - e
 q = (f - e) + (d - c) + (b - a)
 r = ((f - e) / q ) * g
 s = g - ((b - a) / q ) * g

 low = 1
 mid = 1
 high = 1

 i = 1
 while i < 666666:
     x = random.randint(a, b)
     y = random.randint(c, d)
     z = random.randint(e, f)
     v = random.randint(1, g)
     if v < r:
         print(z)
         high += 1
     else:
         if v > s:
             print(x)
             low += 1
         else:
             print(y)
             mid += 1
     i += 1

 print(low, mid, high)



  ...
  72027
  81188
  57 6579 660032

它可以工作,但是非常粗糙,需要我知道哪个列表最长,等等。

2 个答案:

答案 0 :(得分:1)

列出所有输入列表。然后从0到列表的组合长度中选择一个随机数。然后循环遍历列表的增量长度,直到找到索引指向的那个,然后选择该列表的元素。

l1 = [1, 2, 3, 4, 5]
l2 = [10, 20, 30]
l3 = [100, 101, 105, 107, 111, 125, 130]
l4 = [200, 202, 204, 300, 303, 306, 400, 404, 408]
list_of_lists = [l1, l2, l3, l4]
index = random.randint(0, sum(len(l) for l in list_of_lists))
listnum = 0
prev_length = 0
running_length = len(list_of_lists[listnum])
while index >= running_length:
    prev_length = running_length
    listnum += 1
    running_length += len(list_of_lists[listnum])
result = list_of_lists[listnum][index - prev_length]

答案 1 :(得分:0)

只需从串联列表中进行选择,可能无需重新发明轮子并避免索引:

var builder = new ConfigurationBuilder()
                                .SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

IConfigurationRoot _configuration = builder.Build();
var data = _configuration["database_number"]; //it returns null

注意:如果列表的数量有所不同,请列出其中的一个列表并将其传递给chain.from_iterable