Python 获取元组列表的随机样本

Python Get Random Sample of List of Tuples

我有一个超过一百万个元组的列表,并且想要一个从原始列表中随机抽取的 100,000 个元组的列表,而无需替换。我已阅读:

How do I pick 2 random items from a Python set?

但提供的解决方案(使用 random.sample 将列表转换为集合)不适用于元组。

我正在使用 Python 2.7

不确定我是否完全理解你的问题,但是random.sample 可以接受列表和元组:

random.sample([1,2,3,4,5],2)
Out[620]: [2, 5]

random.sample((1,2,3,4,5),2)
Out[621]: [4, 1]

无论元素是否可散列,您都可以对列表进行抽样:

data = create_dataset() # List of data to be sampled

n_samples = 100000
samples = random.sample(data,n_samples)