Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python的列表中找到某个值的随机实例(和索引)_Python_Python 2.7_Random - Fatal编程技术网

如何在python的列表中找到某个值的随机实例(和索引)

如何在python的列表中找到某个值的随机实例(和索引),python,python-2.7,random,Python,Python 2.7,Random,我一直在寻找列表中某个值的所有实例并随机选择一个实例的简单方法 我只想从出现的Value 我在List.index(Value) 但它只返回列表中该值的第一个实例的索引 是否有一些简单的方法可以返回该值所有出现的列表。 例如: 改为选择一个介于0和列表长度之间的随机整数: Instances = List.allindexes(Value) # for example random_index = random.randrange(len(Instances)) random_element

我一直在寻找列表中某个值的所有实例并随机选择一个实例的简单方法

我只想从出现的
Value

我在
List.index(Value)
但它只返回列表中该值的第一个实例的索引

是否有一些简单的方法可以返回该值所有出现的列表。 例如:


改为选择一个介于0和列表长度之间的随机整数:

Instances = List.allindexes(Value)  # for example
random_index = random.randrange(len(Instances))
random_element = Instances[random_index]
现在您既有了索引,也有了它所引用的对象

从您的问题中不清楚列表中的所有元素是否都有资格进行随机选择。如果没有,请使用
enumerate()
并首先筛选列表,然后在筛选的列表上使用
random.choice()

random_index, random_element = random.choice(
    [(i, elem) for (i, elem) in enumerate(Instances) 
     if elem == 'some match'])

我需要的是索引而不是文字值:

Scores = # some list of numbers
Indexes = []
for a in Scores: # iterate through all the scores 
    if a == Value:
        Indexes.append(a) # if the score == Value then add it to the list of viable indexes
FinalIndex = random.choice(Indexes) # Finally choose a random instance of the Value

在Python 3中,获取随机出现的值的索引的正确方法是:

import random
random.choice(list(filter(lambda x: List[x] == Value, range(len(List)))))
这将获取列表中的索引(范围(len(list))),对它们进行过滤,以便只保留值的索引,并随机选择一个

import random
random.choice(list(filter(lambda x: List[x] == Value, range(len(List)))))