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

后端 未结 2 769
礼貌的吻别
礼貌的吻别 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 )
    

提交回复
热议问题