I tried to choose 4 numbers in range(1,6)
using randint
. And I did it using for
loop. But after that I have to write python pytest tests. So I got the problem because after assertion using monkeypatch instead of getting for example [1,2,3,4]
I got [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]]
.
So I want to ask if is possibility to choose 4 items at the same time instead of using randint
4 times.
def throw_a_cube():
a = []
for x in range(4):
x = randint(1, 6)
a.append(x)
return a
CodePudding user response:
No, I don't think it's possible to pick four at once. If you're looking to get four different numbers, your code should look more like this:
import random
def throw_a_cube():
a = []
throws = [1, 2, 3, 4, 5, 6]
for x in range(4):
x = random.choice(throws)
a.append(x)
throws.remove(x)
return a
CodePudding user response:
Simple list comprehension:
import random
def throw_a_cube():
return [random.randint(1,6) for _ in range(4)]
CodePudding user response:
Is this suitable?
from random import choices
throw_a_cube = lambda k: choices(range(1, 6), k=k)
CodePudding user response:
If you find yourself using for loops in Python, there's usually a better way. Probably the simplest in this case is:
from random import choices
def throw_a_cube():
return choices(range(1, 6), k=4)
print(throw_a_cube())
Result:
python 4numbers.py
[2, 5, 1, 5]