Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

python - 如何在Python中弹出一次列表n次?(How to pop() a list n times in Python?)

I have a photo chooser function that counts the number of files in a given directory and makes a list of them.

(我有一个图片选择器功能,可以计算给定目录中的文件数量并列出它们的列表。)

I want it to return only 5 image URLs.

(我希望它仅返回5个图像URL。)

Here's the function:

(功能如下:)

from os import listdir
from os.path import join, isfile

def choose_photos(account):
    photos = []
    # photos dir
    pd = join('C:omgphotos', 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:omgphotos', account, str(p) + '.jpg'))
    return photos
  ask by Timur translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll go ahead and post a couple answers.

(我将继续发布一些答案。)

The easiest way to get some of a list is using slice notation:

(获取列表的最简单方法是使用slice符号:)

pl = pl[:5] # get the first five elements.

If you really want to pop from the list this works:

(如果您真的想从列表中弹出,则可以这样做:)

while len(pl) > 5:
  pl.pop()

If you're after a random selection of the choices from that list, this is probably most effective:

(如果您是从该列表中随机选择选项,那么这可能是最有效的:)

import random
random.sample(range(10), 3)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...