Python中配对列表的随机样本 [英] Random sample of paired lists in Python
本文介绍了Python中配对列表的随机样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表x和y,长度都是n,xi 和 yi 形成一对.我如何从这两个列表中随机抽取 m 个值,同时保留配对信息(例如,x[10] 和 y[10] 将在结果样本中一起出现)
I have two lists x and y, both of length n, with xi and yi forming a pair. How could I take a random sample of m values from these two lists while preserving the pairing information (e.g. x[10] and y[10] would be together in the resulting sample)
我最初的想法是这样.
- 使用 zip 创建元组列表
- 打乱元组列表
- 从列表中选择前 m 个元组
- 将元组分解成新的配对列表
代码看起来像这样.
templist = list()
for tup in zip(x, y):
templist.append(tup)
random.shuffle(templist)
x_sub = [a for a, b in templist[0:m]]
y_sub = [b for a, b in templist[0:m]]
这对我来说似乎很笨拙.有什么方法可以让我更清楚、简洁或 Pythonic 吗?
This seems rather kludgy to me. Is there any way I could make this more clear, concise, or Pythonic?
推荐答案
也许你的意思是采样 m 个元素
maybe you mean sampling m elements
x_sub, y_sub = zip(*random.sample(list(zip(x, y)), m))
这篇关于Python中配对列表的随机样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文