简体   繁体   English

使用Python从列表中选择一个非重复的随机元素

[英]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.

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