Skip to content Skip to sidebar Skip to footer

Python Random Choice From List

How do i choose to pick random choice from the list given below. colours = ['red', 'blue', 'green', 'yellow', 'black', 'purple', 'Brown', 'Orange', 'violet', 'gray'] now pick 1 i

Solution 1:

A simple way would just be to delete the chosen values from the list. It is slightly simpler if you use sets:

In []:
colours = {'red', 'blue', 'green', 'yellow', 'black', 'purple',
           'Brown', 'Orange', 'violet', 'gray'}
for n in [1, 2, 3]:
    cs = random.sample(colours, k=n)
    colours -= set(cs)
    print(cs)

Out[]:
['Brown']
['Orange', 'red']
['purple', 'gray', 'blue']

Solution 2:

colors = ['red', 'blue', 'green', 'yellow', 'black', 'purple','Brown', 'Orange', 'violet', 'gray']
for n inrange(1,4):
    select=np.random.choice(colors,n)
    print(select)
    colors=list(set(colors).difference(set(select)))

output:-['Brown']
        ['red''violet']
        ['yellow''Orange''black']

Solution 3:

The method I use consist in shuffling your input vector take the selected number of elements you need.

import random

colours = ['red', 'blue', 'green', 'yellow', 'black', 'purple', 'Brown', 'Orange', 'violet', 'gray']
random.shuffle(colours)

for i in range(1, 4):
  n, colours = colours[0:i], colours[i:]
  print(n)

Post a Comment for "Python Random Choice From List"