[英]How to generate unique random numbers from a list
I know that I should write a code to random numbers like the code below, but I don't know how to generate unique numbers, for example I want to generate 3 unique phone numbers from a list at once, how can I do it?我知道我应该像下面的代码那样为随机数编写代码,但我不知道如何生成唯一号码,例如我想一次从列表中生成 3 个唯一电话号码,我该怎么做?
import random
# last numbers of the phone numbers are in order, 1,2,3,4,5,6
myList = [60165651, 60175652, 60156523, 60135354, 60159535, 60192326]
for x in range(5):
print(random.choice(myList))
another problem is that if I put zero at the beginning of numbers I get an error: Token invalid!另一个问题是,如果我在数字的开头输入零,我会得到一个错误:令牌无效!
eg:例如:
myPhoneList = [060165651, 60175652, 60156523, 60135354, 60159535, 60192326]
Use random.sample :使用random.sample :
Return ak length list of unique elements chosen from the population sequence or set.
返回从种群序列或集合中选择的唯一元素的长度列表。 Used for random sampling without replacement.
用于无放回的随机抽样。
from random import sample
myList = [60165651, 60175652, 60156523, 60135354, 60159535, 60192326]
print(sample(myList, 3))
# [60192326, 60165651, 60175652]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.