且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-05 16:56:49

使用 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.