简体   繁体   中英

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:

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

random.sample returns a list object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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