“样本大于人口"在random.sample python中 [英] "sample larger than population" in random.sample python

查看:114
本文介绍了“样本大于人口"在random.sample python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为自己创建一个简单的通行证生成器,我注意到,如果我希望我的人口仅是数字(0-9),这是总共10个选项,如果我希望我的长度超过10,它将不再使用任何数字然后一次,然后返回样本数量大于总体数量"错误.

creating a simple pass generator for myself, i noticed that if i want my population to be digits only (0-9) which is overall 10 options, if i want my length over 10, it wont use any of the digits more then once and return the "sample larger then population" error.

是否可以维护代码,但添加/减少代码行以使其起作用?还是我必须使用使用随机选择?

is it possible to maintain the code, but add/reduce code lines so it works? or do i HAVE To use a use random choice?

import string
import random

z=int(raw_input("for: \n numbers only choose 1, \n letters only choose 2, \n letters and numbers choose 3, \n for everything choose 4:"))

if z==1:
    x=string.digits
elif z==2:
    x=string.letters
elif z==3:
    x=string.letters+string.digits
elif z==4:
    x=string.letters+string.digits+string.punctuation
else:
    print "die in a fire"

y=int(raw_input("How many passwords would you like?:"))
v=int(raw_input("How long would you like the password to be?:"))

for i in range(y):
    string=""
    for n in random.sample(x,v):
        string+=n
    print string

ty

推荐答案

random.sample()目的是随机选择输入序列的子集.挑选一个以上的元素不止一次.如果您的输入序列没有重复,那么您的输出也不会重复.

The purpose of random.sample() is to pick a subset of the input sequence, randomly, without picking any one element more than once. If your input sequence has no repetitions, neither will your output.

不是正在寻找子集;您希望从输入序列中选择单个随机选择,并重复多次.元素可以多次使用.为此,请在循环中使用random.choice()

You are not looking for a subset; you want single random choices from the input sequence, repeated a number of times. Elements can be used more than once. Use random.choice() in a loop for this:

for i in range(y):
    string = ''.join([random.choice(x) for _ in range(v)])
    print string

这将创建一个长度为v的字符串,其中x中的字符可以多次使用.

This creates a string of length v, where characters from x can be used more than once.

快速演示:

>>> import string
>>> import random
>>> x = string.letters + string.digits + string.punctuation
>>> v = 20
>>> ''.join([random.choice(x) for _ in range(v)])
'Ms>V\\0Mf|W@R,#/.P~Rv'
>>> ''.join([random.choice(x) for _ in range(v)])
'TsPnvN&qlm#mBj-!~}3W'
>>> ''.join([random.choice(x) for _ in range(v)])
'{:dfE;VhR:=_~O*,QG<f'

这篇关于“样本大于人口"在random.sample python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆