Python 3:如何获得一个随机的 4 位长数字,该数字内没有重复的数字?

1 python random numbers python-3.x

好的,所以我需要我的程序能够获得一个在该数字中没有重复数字的随机数。所以像 0012 有两个 0,因此我不需要那个,但是,1234 可以工作。这些数字也需要只有 4 位数字长。

import random
Run Code Online (Sandbox Code Playgroud)

Aar*_*ron 5

您可以使用示例:

import random
numbers = random.sample(range(10), 4)
print(''.join(map(str, numbers)))
Run Code Online (Sandbox Code Playgroud)

@Copperfield 注释中的变体很优雅,因为它不需要进行转换(因为您是从字符串中采样)。

import random
number = ''.join(random.sample("0123456789", 4))
print(number)
Run Code Online (Sandbox Code Playgroud)

  • 一种变体:`''.join(random.sample("0123456789", 4))` (3认同)