1

## 如何在Python的random中增加限制?

``````import random
random.sample ( ['apple', 'pear', 'peach', 'orange', 'lemon', 'peach'],3)
``````

suasem iT邦新手 5 級 ‧ 2018-10-24 14:15:24 檢舉

random.sample ( set(['apple', 'pear', 'peach', 'orange', 'lemon', 'peach']),3)

random.sample ( {'apple', 'pear', 'peach', 'orange', 'lemon', 'peach'},3)

### 3 個回答

0

iT邦新手 5 級 ‧ 2018-10-26 12:41:18

``````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的重複元素。

1
froce
iT邦高手 1 級 ‧ 2018-10-24 11:46:55
``````options = ['apple', 'pear', 'peach', 'orange', 'lemon', 'peach']
random.shuffle(options)
print(options[:3])
``````

``````random.sample ( ['apple', 'pear', 'peach', 'orange', 'lemon', 'peach'], k=3)
``````
vsu91267 iT邦新手 5 級 ‧ 2018-10-24 12:56:22 檢舉

youarefat iT邦新手 5 級 ‧ 2018-10-25 14:42:51 檢舉

options就其他的隨便取兩個或三個?

0
Jack
iT邦新手 5 級 ‧ 2018-11-07 15:16:16
``````import random
fruit = ['apple', 'pear', 'peach', 'orange', 'peach']

print(random.sample(set(fruit),3))
``````