import numpy as np
x = [1,2,3,4,5,6,7,8,9]
y = [11,12,13,14,15,16,17,18,19]
我有一个元组列表如下:
xy = [(x,y) for x,y in zip(x,y)]
现在我想随机选择列表中元组的3个位置/索引。
random_indices = np.random.choice(len(xy),3,replace=False)
这里我应用了索引来返回SELECTED元组的列表:
selected_xy = xy[random_indices]
print selected_xy
但我收到以下错误:
Traceback (most recent call last):
File "D:/test.py", line 11, in <module>
selected_xy = xy[random_indices]
TypeError: only integer arrays with one element can be converted to an index
我的目标是从列表中随机选择元组,预期结果应该如下所示:
[(1,11),(3,13),(4,14)]
这样做的最佳方式是什么?
答案 0 :(得分:3)
将xy
转换为NumPy数组,仅列出支持带整数的索引:
>>> xy = np.array([(a, b) for a, b in zip(x, y)])
>>> random_indices = np.random.choice(len(xy), 3,replace=False)
>>> xy[random_indices]
array([[ 7, 17],
[ 2, 12],
[ 4, 14]])
在Python中,您可以使用operator.itemgetter
或在列表推导中循环索引来执行此操作,并在该索引处获取项目:
>>> from operator import itemgetter
>>> xy = [(a, b) for a, b in zip(x, y)]
>>> random_indices = np.random.choice(len(xy), 3, replace=False)
>>> itemgetter(*random_indices)(xy)
((2, 12), (1, 11), (4, 14))