random.choice from set? python

前端 未结 2 2104
渐次进展
渐次进展 2020-12-08 03:28

I\'m working on an AI portion of a guessing game. I want the AI to select a random letter from this list. I\'m doing it as a set so I can easily remove letters from the list

相关标签:
2条回答
  • 2020-12-08 04:03
    >>> random.sample(set('abcdefghijklmnopqrstuvwxyz'), 1)
    ['f']
    

    Documentation: https://docs.python.org/3/library/random.html#random.sample

    0 讨论(0)
  • 2020-12-08 04:19

    You should use random.choice(tuple(myset)), because it's faster and arguably cleaner looking than random.sample. I wrote the following to test:

    import random
    import timeit
    
    bigset = set(random.uniform(0,10000) for x in range(10000))
    
    def choose():
        random.choice(tuple(bigset))
    
    def sample():
        random.sample(bigset,1)[0]
    
    print("random.choice:", timeit.timeit(choose, setup="global bigset", number=10000)) # 1.1082136780023575
    print("random.sample:", timeit.timeit(sample, setup="global bigset", number=10000)) # 1.1889629259821959
    

    From the numbers it seems that random.sample takes 7% longer.

    0 讨论(0)
提交回复
热议问题