Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a list of 50 random colours in python?

Given colour = [ "red", "blue", "green", "yellow", "purple", "orange", "white", "black" ] generate and print a list of 50 random colours. You will need to use the random module to get random numbers. Use range and map to generated the required amount of numbers. Then use map to translate numbers to colours. Print the result.

This is a question i've been given and here's my code so far

colour = [ "red", "blue", "green", "yellow", "purple", "orange", "white", "black" ]

number=random.randint(1,9)

number.range(50)

i'm assuming this has made a variable that picks random numbers between 1-9, and then makes 50 of them ? i now need some way of linking the numbers to the colours.. i know this question is quite vague but if anyone could point me in the right direction, that would be awesome !

like image 739
Carla Dessi Avatar asked Jan 29 '12 22:01

Carla Dessi


2 Answers

What you need is to use random.choice(seq) 50 times passing it colour list as argument.

Like this:

 rand_colours = [random.choice(colour) for i in range(50)]

random.choice(seq) returns randomly selected element from seq.

like image 161
soulcheck Avatar answered Sep 30 '22 03:09

soulcheck


If you want n random hex colors, try this:

import random
get_colors = lambda n: list(map(lambda i: "#" + "%06x" % random.randint(0, 0xFFFFFF),range(n)))
get_colors(5) # sample return:  ['#8af5da', '#fbc08c', '#b741d0', '#e599f1', '#bbcb59', '#a2a6c0']
like image 30
Jaden Travnik Avatar answered Sep 30 '22 01:09

Jaden Travnik