如何随机选择列表的值?

时间:2017-11-16 04:04:35

标签: python python-2.7 random

我使用的是Python 2.7

要明确,我不想随机化列表中的项目。我想这样做,以便某些字符串根本不显示。例如:

import pygame as pg


class Player(pg.sprite.Sprite):

    def __init__(self, pos):
        super().__init__()
        self.image = pg.Surface((30, 50))
        self.image.fill(pg.Color('dodgerblue2'))
        self.rect = self.image.get_rect(center=pos)


class Game:

    def __init__(self):
        self.screen = pg.display.set_mode((640, 480))
        self.clock = pg.time.Clock()
        self.all_sprites = pg.sprite.Group(Player((200, 200)), Player((400, 200)))
        self.done = False

    def run(self):
        while not self.done:
            self.handle_events()
            self.run_logic()
            self.draw()
            self.clock.tick(30)

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True
            elif event.type == pg.MOUSEBUTTONUP:
                if event.button == 1:  # Left mouse button.
                    for sprite in self.all_sprites:
                        if sprite.rect.collidepoint(event.pos):
                            sprite.kill()

    def run_logic(self):
        self.all_sprites.update()

    def draw(self):
        self.screen.fill((30, 30, 30))
        self.all_sprites.draw(self.screen)
        pg.display.flip()


if __name__ == '__main__':
    pg.init()
    Game().run()
    pg.quit()

显然上面的代码不起作用,但我不确定如何继续。如果我可以改变选择某个字符串的可能性,例如50%的红色赔率,30%的蓝色赔率和20%的黄色赔率,也会有所帮助。

2 个答案:

答案 0 :(得分:3)

您可以使用numpy.random.choicep参数允许您指定与每个条目关联的概率。

import numpy as np

r, b, y = 'red', 'blue', 'yellow'
my_colours = np.random.choice(a=[r, b, y], size=3, p=[.5, .3, .2])
print(my_colours) . # my_colours.tolist() if you want list output
# ['yellow' 'red' 'red']

要确认这是有效的,请使用大小为30,000而不是3的结果,并让大数定律做其事。

from collections import Counter

test = np.random.choice(a=[r, b, y], size=30000, p=[.5, .3, .2])
counts = Counter(test)

# Relative occurences:
dict(zip(counts.keys(), [count/30000 for count in counts.values()]))
{'blue': 0.30483333333333335,
 'red': 0.5000333333333333,
 'yellow': 0.19513333333333333}

答案 1 :(得分:1)

虽然使用Python 2.7无法帮助OP,但对于那些使用 Python 3.6 的用户来说,random.choices很简单,包含权重并且是标准库的一部分。

  

返回从替换人群中选择的k大小的元素列表。

鉴于

import random


r = "red"
b = "blue"
y = "yellow"

iterable = r, b, y
size = 3
wts = [.5, .3, .2]

代码

random.choices(iterable, k=size)
# ['red', 'yellow', 'yellow']

random.choices(iterable, weights=wts, k=size)
# ['red', 'red', 'red']