首页 > 解决方案 > 如何制作索引的随机组合列表?

问题描述

在这里,我有一个包含大约 6000 个元素的列表。(1~6000)

我正在尝试对其索引进行组合,但 6000 组合 2 几乎有 2000 万例。

因此,除了计算所有可能的 2000 万个组合案例之外,我还想随机组合具有较少案例的组合,例如 5 或 300 万个案例。

def binary_indexing(dataframe):
    # Dataframe has almost 6000 rows
    numList = list(range(len(dataframe)))
    
    # Calculating below code takes too much time since it has immense number of cases.
    indexList = list(combinations(numList , 2))

我试过使用import randomand randomList = random.sample(indexList, len(indexList))

但由于无论如何它必须计算所有可能的组合,所以效果不佳。

标签: pythonlistcombinations

解决方案


如果您想要两个数字的 3,000,000 个组合,您可以将 6000 个数字中的每一个与 500 个数字的随机样本配对,如下所示:

import random
lst = [i for i in range(6000)]
sample = random.sample(lst, 500)
combos = [(i, j) for i in lst for j in sample]

print(f'First 10 combos: {combos[:10]}')
#First 10 combos: [(0, 842), (0, 4387), (0, 3198), (0, 1907), (0, 5332), (0, 4923), (0, 5802), (0, 1346), (0, 197), (0, 2885)]

print(len(combos))
#3000000

推荐阅读