Python Random.Choice EXCEPT One Option
Asked Answered
H

3

6

I am trying to use random.choice() to select an item from a dictionary, however, I would like one of the items to be ignored entirely. For example:

mutationMarkers = {0: "original", 1: "point_mutation", 2: "frameshift_insertion", 
                   3: "frameshift_deletion", 4: "copy_number_addition", 
                   5: "copy_number_subtraction"}

mutator = choice(list(markers)) # output is 0, 1, 2, 3, 4, 5

Is it possible to use random.choice and ignore {0: "original"}?

Hysterectomy answered 9/5, 2018 at 8:18 Comment(0)
V
10

You can use a list comprehension:

mutator = choice([x for x in mutationMarkers if x != 0])
Verdict answered 9/5, 2018 at 8:21 Comment(3)
@BcK I don't think performances will be an issue for a 5 elements list...Exempt
@BcK, well, you can also define the list elsewhere and reuse it if you have to call choice() repeatedly.Verdict
@jpp Explicit is better than implicit :)Verdict
R
3

An alternative solution using set:

mutator = choice(tuple(mutationMarkers.keys() - {0}))
Rang answered 9/5, 2018 at 9:31 Comment(0)
T
-1

You can also use random.choices instead and provide zero weights for those elements that you want to drop.

In [1]: import random

In [2]: a = ["a", "b", "c", "d", "e"]

In [3]: n = len(a)

In [4]: weights = [1./(n-1) if _ != "c" else 0 for _ in a]

In [5]: random.choices(a, weights=weights, k=10)
Out[5]: ['e', 'd', 'b', 'e', 'a', 'd', 'd', 'd', 'b', 'b']
Tertia answered 28/2 at 3:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.