我需要生成一个完全随机的4位数字,但其中没有数字彼此相等

时间:2016-10-12 03:57:17

标签: python-3.x

import random 

D1=str(random.randint(0,9))
D2=str(random.randint(0,9))
D3=str(random.randint(0,9))
D4=str(random.randint(0,9))

while D1!=D2 and D1!=D3 and D1!=D4 and D2!=D3 and D2!=D4 and D3!=D4:
    secret=D1+D2+D3+D4
    print(secret)

一旦我打印,它就会持续运行,但我想让它停止输出一次

2 个答案:

答案 0 :(得分:1)

digits = random.sample(string.digits, 4)  # ['8', '9', '0', '6']
print("".join(digits))                    # '8906'

答案 1 :(得分:0)

您可以使用下面定义的函数each_choice_different从指定的序列seq生成n个选项的随机列表,其中不会重复选择:

def each_choice_different(seq, n):
    """
    Returns a list in which each element is randomly chosen from `seq`
    and no choice is repeated.

    seq : the sequence from which to make choices
    n   : the number of choices to make (should not be greater than the
          number of elements in `seq`)
    """

    seq = list(seq)
    assert 0 < n <= len(seq)
    lst = []
    for _ in range(n):
        c = random.choice(seq)
        lst.append(c)
        seq.remove(c)
    return lst

four_digits_different = lambda : sum((d*10**i for i, d in 
    enumerate(each_choice_different(range(10), 4))))

# generate 7 random numbers; no digit in each of these numbers is repeated
print([four_digits_different() for _ in range(7)])

# I got:
# [8094, 2105, 7364, 1643, 3064, 6835, 1326]