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

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

问题描述:

我有此列表:

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?

使用 random.sample 选择随机的非重复元素:

Use random.sample to choose random non-repeating elements:

>>> import random
>>> random.sample(glob.glob('*.jpg'), number_of_images_to_choose)

random.sample返回list对象.

旁注:不需要列表理解,除非您打算过滤glob.glob的结果.

Side note: there's no need in list comprehension, unless you're planning to filter the result of glob.glob.