[英]Choose a non-repeating random element from a list using Python
I have this list: 我有这个清单:
pics = [i for i in glob.glob("*.jpg")]
choice = random.choice(pics)
and the code below the list was used to select a random image from a list. 并且列表下方的代码用于从列表中选择随机图像。 My problem is that it isn't unique and lots of pictures repeat.. Is there any way to overcome that? 我的问题是,它不是唯一的,很多图片重复..有没有办法克服这个?
Use random.sample
to choose random non-repeating elements: 使用random.sample
选择随机非重复元素:
>>> import random
>>> random.sample(glob.glob('*.jpg'), number_of_images_to_choose)
random.sample
returns a list
object. random.sample
返回一个list
对象。
Side note: there's no need in list comprehension, unless you're planning to filter the result of glob.glob
. 旁注:除非您计划过滤glob.glob
的结果,否则不需要列表glob.glob
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.