我有一个照片选择器函数,它可以计算给定目录中文件的数量,并将它们列成列表。我希望它只返回5个图像URL。以下是该函数:
from os import listdir
from os.path import join, isfile
def choose_photos(account):
photos = []
# photos dir
pd = join('C:\omg\photos', account)
# of photos
nop = len([name for name in listdir(location) if isfile(name)]) - 1
# list of photos
pl = list(range(0, nop))
if len(pl) > 5:
extra = len(pl) - 5
# How can I pop extra times, so I end up with a list of 5 numbers
shuffle(pl)
for p in pl:
photos.append(join('C:\omg\photos', account, str(p) + '.jpg'))
return photos
pl[:5]
。切片操作会返回前五个元素。 - g.d.d.crandom.sample
。 - Martijn Pieters