我嘗試在range(1,6)使用中選擇 4 個數字randint。我是用for回圈來做的。但在那之后我必須撰寫 python pytest 測驗。所以我遇到了問題,因為在使用monkeypatch 斷言而不是例如[1,2,3,4]我得到了[[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]].
所以我想問一下是否可以同時選擇4個專案而不是使用randint4次。
def throw_a_cube():
a = []
for x in range(4):
x = randint(1, 6)
a.append(x)
return a
uj5u.com熱心網友回復:
不,我認為不可能一次選擇四個。如果您想獲得四個不同的數字,您的代碼應該更像這樣:
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
uj5u.com熱心網友回復:
簡單的串列理解:
import random
def throw_a_cube():
return [random.randint(1,6) for _ in range(4)]
uj5u.com熱心網友回復:
這個合適嗎?
from random import choices
throw_a_cube = lambda k: choices(range(1, 6), k=k)
uj5u.com熱心網友回復:
如果您發現自己在 Python 中使用 for 回圈,通常有更好的方法。在這種情況下,最簡單的可能是:
from random import choices
def throw_a_cube():
return choices(range(1, 6), k=4)
print(throw_a_cube())
結果:
python 4numbers.py
[2, 5, 1, 5]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/376185.html
