我想从列表的随机元素中列出固定数量的值。我得到了一个错误:
import random
ALL_COLORS = ("red", "green", "blue", "yellow", "orange", "white")
def create_combination(nb_elements):
i = 0
combination = ""
while i < nb_elements:
combination += random.choice(ALL_COLORS)
i += 1
print(combination, sep=", ")
return (combination)
for i in range(10):
combination = create_combination
assert len(combination) == i
for color in combination:
assert color in ALL_COLORS
答案 0 :(得分:1)
您的代码过于复杂。
以下是一种可以实现您可能需要的方法:
import random
colours = ("red", "green", "blue", "yellow", "orange", "white")
result = [random.choice(colours) for _ in range(10)]
# Example output
# ['orange', 'red', 'blue', 'yellow', 'green', 'red', 'yellow', 'white', 'orange', 'red']
现有代码存在许多问题,使其无法使用: