Python:列表中的非重复随机值 [英] Python: Non repeating random values from list

查看:118
本文介绍了Python:列表中的非重复随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用python 2.7编写一个程序,该程序必须选择多个随机变量并将其打印出来.但是该变量不能与任何先前打印出的变量相同.

I am trying to write a program in python 2.7 that has to choose more than one random variable and print it out. But the variable can't be the same as any of the previously printed out variables.

我一直在寻找Google和这个网站,但是我还没有找到关于字符串的任何东西(到目前为止,我只发现了整数).这是一个示例:

I have been looking around Google and this site, and I have yet to find anything for strings (I have only found integers so far). Here is an example:

sentences = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p]
print (random.choice(sentences)) + (random.choice(sentences)) + (random.choice(sentences))

>>> a + b + a

我不想重复,我希望它像这样:

I don't want there to be duplicates, I want it to be like this:

>>> a + b + c

有什么方法可以实现?

推荐答案

您可以使用random.sample()

random.sample(population, k)

返回从population序列中选择的唯一元素的k长度列表.用于随机抽样而无需替换.

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

In [13]: "+".join(random.sample(sentences,3))
Out[13]: 'a+b+c'

这篇关于Python:列表中的非重复随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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