How to put () a list n times in Python?

I have a photo selection 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. Here's the function:

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
+5
source share
3 answers

I will tell a couple of answers. The easiest way to get some list is to use the notation slice:

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

If you really want to jump out of the list, this works:

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

If you are after a random selection of options from this list, this is probably the most effective:

import random
random.sample(range(10), 3)
+6
source

Since this is a list, you can simply get the last five elements by cutting it off:

last_photos = photos[5:]

, . , .

import copy
last_photos = copy.deepcopy(photos)[5:]

:

, [5:] [: -5] "" 5 , , 5 ...

+3

In most languages, pop () removes and returns the last item from the collection. So, to simultaneously remove and return n elements, how about:

def getPhotos(num):
    return [pl.pop() for _ in range(0,num)]
0
source

All Articles