【发布时间】:2016-04-21 20:24:24
【问题描述】:
以下简单代码为我提供了 200 个元素中长度为 3 的可能组合。
from itertools import combinations
comb = combinations( range(200), 3 )
我想以随机顺序获取组合,以便选择前 N 个组合。但是,如果我将 comb 转换为列表并按以下方式对其进行随机播放,则可能会出现内存错误,因为列表可能包含太多元素:
comb = list(comb) # This might be huge and give a memory error
random.shuffle(comb)
N = 10
comb = comb[:10] # get only the first N random combinations
还有其他方法可以得到 N 个随机组合吗? (即,不是按照 itertools.combinations 生成的顺序)。
【问题讨论】:
标签: python combinations shuffle itertools