拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 获取串列的组合,其中它选择串列中和下面的当前数字

获取串列的组合,其中它选择串列中和下面的当前数字

白鹭 - 2022-03-04 1949 0 0

我正在尝试获取所有数字组合,但它有点复杂,所以我将通过示例展示:

假设我有一个类似 [5, 10, 12, 4, 6] 的串列,我想要 [1, 1, 1, 1, 1], [1, 2, 1, 1, 1], ... [ 5、10、12、4、6]

所以每个数字只会上升到它的最高点。我试过这个:

def listdir_nohidden(path):
  for f in os.listdir(path):
    if not f.startswith('.'):
      yield f

def listdir(path):
  return list(listdir_nohidden(path))

def listlen(path):
  return len(list(listdir_nohidden(path)))

def randomiser(filename):
  return random.randint(1,listlen(f'./{filename}'))

lengths = []
i = 0
while i < 5:
  lengths.append(listlen(f'./{i}'))
  i  = 1
print(lengths) # ['5', '16', '16', '16', '6']

random_array = []
j = 0
while j < 30:
  random_array.append([randomiser(0), randomiser(1), randomiser(2), randomiser(3), randomiser(4)])
  j  = 1

但是有重复的机会,它并不是真正随机的。我知道串列中的数字足够高,机会非常渺茫,但我实际上想生成很多这样的数字,所以重复的机会就会增加。

uj5u.com热心网友回复:

怎么用itertools.product

import itertools

lst = [5, 10, 12, 4, 6]

output = list(itertools.product(*(range(1, k 1) for k in lst)))
print(output[:5]) # first five: [(1, 1, 1, 1, 1), (1, 1, 1, 1, 2), (1, 1, 1, 1, 3), (1, 1, 1, 1, 4), (1, 1, 1, 1, 5)]
print(output[-5:]) # last five: [(5, 10, 12, 4, 2), (5, 10, 12, 4, 3), (5, 10, 12, 4, 4), (5, 10, 12, 4, 5), (5, 10, 12, 4, 6)]
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *