从列表/ 1D数组和值索引中随机提取值

时间:2018-04-20 15:55:14

标签: python arrays

我有一个1D数组/列表,其中100个值从1-20随机混洗。

我想随机选择其中两个值和该值的索引。

这些值的索引将用于访问第二个列表中的两个值。

到目前为止,我有:

list1=[]
for i in range (2):
a=random.sample(Values) #Values is the name of the array with shuffled values 1-100
list1.append(a) #this holds the two random values

此时a持有: A = [2,5]

这是两个随机选择的值,但无论如何都要访问它们的索引? 2和5都在Values数组中多次显示。

我在想字典方法可能有意义: a = {2:6,5:25} 保持价值和指数。在这种情况下,索引6和25可用于访问第二个列表中的值。

我不确定如何编码,有人会有一些见解吗?

2 个答案:

答案 0 :(得分:2)

由于您对索引感兴趣,因此更容易做相反的事情:生成随机索引,然后使用它们来检索值:

import random
indexes = random.sample(range(len(Values)), 2) # get two random indexes
list1 = [Values[n] for n in indexes]

按照您的示例,这将返回[6, 25]变量中的indexes,然后检索[2, 5]变量的list1

答案 1 :(得分:1)

您可以从range(len(Values))

进行抽样
list1_idx = []
list1 = []
for i in range (2):
    sampled_idx = random.sample(range(len(Values)))
    list1_idx.append(sampled_idx)
    list1.append(Values[sampled_idx])

或更简单:

list1_idx = [random.sample(range(len(Values))) for i in range(2)]
list1 = [Values[i] for i in list1_idx]

请注意,这将对替换的两个元素进行采样,也就是说,您可以获得两次相同的索引。如果您想对两个不同的元素进行采样,请尝试:

list1_idx = random.sample(range(len(Values)), 2)
list1 = [Values[i] for i in list1_idx]