Python 随机选择,除了一个选项

问题描述 投票:0回答:3

我正在尝试使用

random.choice()
从字典中选择一个项目,但是,我希望完全忽略其中一个项目。例如:

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

是否可以使用

random.choice
并忽略
{0: "original"}

python dictionary random
3个回答
10
投票

您可以使用列表理解:

mutator = choice([x for x in mutationMarkers if x != 0])

3
投票

使用

set
的替代解决方案:

mutator = choice(tuple(mutationMarkers.keys() - {0}))

0
投票

您还可以使用

random.choices
来代替,并为那些要删除的元素提供零权重。

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']
© www.soinside.com 2019 - 2024. All rights reserved.