python - 如何制作索引的随机组合列表?
问题描述
在这里,我有一个包含大约 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 random
and randomList = random.sample(indexList, len(indexList))
。
但由于无论如何它必须计算所有可能的组合,所以效果不佳。
解决方案
如果您想要两个数字的 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
推荐阅读
- laravel - 如何使用 laravel 中的一个函数在同一个文件中加载两个不同的视图
- python - 如何使用具有多个处理程序的 Python 日志记录模块将一条日志记录发送到文件,并将另一条日志记录发送到电子邮件
- python-3.x - 不确定tic_tac_toe换板
- java - 使用 Java 批量上传到 Box*
- javascript - 如何使用 JS 和 DOM 创建元素、设置属性、使用 innerHTML 和 appendChild
- c# - 如何从方法返回一些东西以打破 C# 中的循环?
- javascript - req.isAuthenticated() 重定向更改?
- azure - Azure“文本转语音”返回“无效的 CID 或语言”。这是什么意思?
- dictionary - 如何链接 LinkedList 节点以映射值
- opengl - GLFW_TRANSPARENT 和 GLFW_ALPHA_MASK 未定义