How can you select a random element from a list, and have it be removed?

后端 未结 2 768
礼貌的吻别
礼貌的吻别 2021-01-20 23:47

Let\'s say I have a list of colours, colours = [\'red\', \'blue\', \'green\', \'purple\'].
I then wish to call this python function that I hope exists, ra

相关标签:
2条回答
  • 2021-01-20 23:55

    one way:

    from random import shuffle
    
    def walk_random_colors( colors ):
      # optionally make a copy first:
      # colors = colors[:] 
      shuffle( colors )
      while colors:
        yield colors.pop()
    
    colors = [ ... whatever ... ]
    for color in walk_random_colors( colors ):
      print( color )
    
    0 讨论(0)
  • 2021-01-21 00:12

    Firstly, if you want it removed because you want to do this again and again, you might want to use random.shuffle() in the random module.

    random.choice() picks one, but does not remove it.

    Otherwise, try:

    import random
    
    # this will choose one and remove it
    def choose_and_remove( items ):
        # pick an item index
        if items:
            index = random.randrange( len(items) )
            return items.pop(index)
        # nothing left!
        return None
    
    0 讨论(0)
提交回复
热议问题