Python-提取器上的lottonum重复

时间:2018-07-28 09:15:05

标签: python

import random

lotto = []
while True:
    a = random.randint(1, 45)
    lotto.append(a)
    if lotto.count(a) == 2:
        continue
    if len(lotto) == 7:
        break
lotto.sort()
print(lotto)

我想提取1到45个没有重复的数字,但有时有两个或三个随机数重叠。感谢帮助。

2 个答案:

答案 0 :(得分:0)

您可以创建另一个列表,该列表将保存所有已选择的数字并检查重复项:

import random

lotto = []
# List that will hold all chosen numbers so far
dups = []
while True:
    a = random.randint(1, 45)
    # Check for duplicate number
    if a in dups:
        continue
    else:
        #Add it to both dups and lotto
        dups.append(a)
        lotto.append(a)

    if len(lotto) == 7:
        break

lotto.sort()
print(lotto)

答案 1 :(得分:0)

为此目的,存在random.sample

lotto = sorted(random.sample(range(1, 46), 7))