pythonic way of selecing a random value that satisfies a certain predicate
Posted
by MK
on Stack Overflow
See other posts from Stack Overflow
or by MK
Published on 2010-05-14T16:18:17Z
Indexed on
2010/05/14
16:24 UTC
Read the original article
Hit count: 395
Suppose I have a list of elements and I want to randomly select an element from the list that satisfies a predicate. What is the pythonic way of doing this?
I currently do a comprehension followed by a random.choice()
but that is unnecessarily inefficient :
intlist = [1,2,3,4,5,6,7,8,9]
evenlist = [ i for i in intlist if i % 2 == 0 ]
randomeven = random.choice(evenlist)
Thanks!
© Stack Overflow or respective owner