0
Generate a random number
Hello in my code I need to generate a list of numbers in range 1 to 9 which I use the random module but I wander how to make it work so that the numbers are appended into an list: x = [lambda x: x for x in random.randrange(1,9)]
4 ответов
+ 2
Then there are some mistakes in your code:
1) randrange(1, 9) never returns 9. (You should use randrange(1, 10) or randint(1, 9) instead
2) Where is the list length (which is 6) in your code?
3) you can generate list by list comprehension, but the values won't be unique. For example:
x = [random.randrange(1,10) for x in range(6)]
or:
x = [random.randint(1,9) for x in range(6)]
Both the lines return the list with unique values
I would suggest to try random.shuffle instead.
*UPDATE: random.sample is the better sggestion in this case. Thanks to Jay Matthews
0
daniel
1) How many numbers you want to put in the list?
2) Do the numbers have to be unique?
3) Is 9 included in the range?
0
i want to put 6 numbers that are unique and yes 9 might be part of the list.
0
random.sample works with range as well:
x=random.sample(range(1,10),6)