python django随机选择一个值除外

时间:2015-02-03 16:39:01

标签: python django random

我有一个观点:

winner = random.choice(player_list)

try:
    check_winner = Winner.objects.get(phone_no=9899889988)
    if check_winer:
        winner = random.choice(player_list)
    else:
        winner = winner
except Winner.DoesNotExist:
    pass

这里我想要的是如果check_winner存在然后再次从玩家中随机选择获胜者但不包括check_winner

如何从随机播放列表中排除某些值

1 个答案:

答案 0 :(得分:0)

在[0,len(player_list)-2]中选择一个随机数。如果数字是> = player_list.index(check_winner),则将其值增加1。那就是:

rand_player = random.randint(0, len(player_list) - 2)
if(player_list.index(check_winner) <= rand_player):
    rand_player+= 1
winner = player_list[rand_player]

当然,这很糟糕,因为它的复杂性是O(n)

如果您知道索引check_winner它将是常量。

这个想法是,你在所有其他玩家之间随机选择,只需跳过check_winner