简体   繁体   English

如何在Python中生成一个带有REPETITION的随机列表?

[英]How do I generate a random list WITH REPETITION in Python?

I want to generate a random list with repetition and I do not know how it is done, because it always gives me error, I write this: 我想生成一个带有重复的随机列表,但我不知道它是如何完成的,因为它总是给我错误,我这样写:

  1. x=rm.sample(range(1001), 2000) x = rm.sample(范围(1001),2000)
  2. print(x) 打印(x)

I want a list of 2000 numbers between 1 and 100 我想要2000到1到100之间的数字的列表

Help me pls. 请帮助我。

You can just use the random library and a list comprehension. 您可以只使用随机库和列表推导。

import random
[random.randint(1,100) for x in range(2000)]

If you'd like to print that list, you can assign it a value and print it as you've done in your question. 如果您想打印该列表,则可以为其分配一个值,然后按照问题的答案进行打印。

import random
x = [random.randint(1,100) for x in range(2000)]
print x

EDIT: Based on OP's comment below: If you'd like to remove all values under 50, you can do it while you're generating the initial list and not generate them at all. 编辑:基于OP的以下注释:如果要删除所有小于50的值,则可以在生成初始列表时执行,而根本不生成它们。

import random
[random.randint(50,100) for x in range(2000)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM