我有一个照片选择器功能,它计算给定目录中的文件数量并列出它们.我希望它只返回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
Run Code Online (Sandbox Code Playgroud)
我会继续发一些答案.获取列表的最简单方法是使用slice表示法:
pl = pl[:5] # get the first five elements.
Run Code Online (Sandbox Code Playgroud)
如果你真的想从列表中弹出,这可行:
while len(pl) > 5:
pl.pop()
Run Code Online (Sandbox Code Playgroud)
如果您在随机选择该列表中的选项后,这可能是最有效的:
import random
random.sample(range(10), 3)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5829 次 |
| 最近记录: |