使用Python从列表中选择一个非重复的随机元素 [英] Choose a non-repeating random element from a list using Python

查看:489
本文介绍了使用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.

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

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