簡體   English   中英

如何在python的列表中找到某個值的隨機實例(和索引)

[英]How do I find a random instance (and index) of a certain value in a list in python

我堅持使用一種簡單的方法來查找列表中某個值的所有實例並隨機選擇一個。

我只想從Value的出現中選擇

我在List.index(Value)上找到了一些東西,但它只返回我列表中該值的第一個實例的索引。

是否有一些簡單的方法可以返回所有出現的值的列表。 例子:

Instances = List.allindexes(Value)  # for example
SelectedIndex = random.choice(Instances) # select a random instance of 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)))))

這需要您的列表中的索引 (range(len(List))),過濾它們,以便只保留 Value 的索引並隨機選擇一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM