小弟想到兩種方式
如果在高手眼中太拙劣請見諒
import random
options = ['apple', 'pear', 'peach', 'orange', 'peach']
def ver1(n):
for i in range(n):
a = random.sample(options,3)
if a.count('peach') > 1:
continue
else:
print(a)
def ver2(n):
for i in range(n):
set_obj = set(options)
b = random.sample(set_obj, 3)
print(b)
ver1是以count()過濾掉出現兩次的情況。
ver2則是以set()內元素不會重複的特性,過濾掉原本list的重複元素。
options = ['apple', 'pear', 'peach', 'orange', 'lemon', 'peach']
random.shuffle(options)
print(options[:3])
或
random.sample ( ['apple', 'pear', 'peach', 'orange', 'lemon', 'peach'], k=3)
import random
fruit = ['apple', 'pear', 'peach', 'orange', 'peach']
print(random.sample(set(fruit),3))