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吗?
您可以使用以下代码对 m 对进行采样并将它们分成两个列表:
import random
x = list(range(1, 10))
y = list("abcdefghij")
m = 3
x_sub, y_sub = zip(*random.sample(list(zip(x, y)), m))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)