random.choice prints always the same result

Viewed 64

i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files list.

To do so, i'm using this line of code:

minio = Minio('myip',
                access_key='mykey',
                secret_key='mykey',
              )

images = minio.list_objects('mybucket', recursive=True)

for img2 in images:
    names = img2.object_name

print(random.choice([names]))

Everytime i try to run it, it prints always the same file's name (c81d9307-7666-447d-bcfb-2c13a40de5ca.png)

I tried to put the "print" function in the "for" block, but it prints out both of the files' names

4 Answers

You are setting the variable names to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead.

For example:

names = [img2.object_name for img2 in images]

print(random.choice(names))
minio = Minio('myip',
                access_key='mykey',
                secret_key='mykey',
              )

images = minio.list_objects('mybucket', recursive=True)
names = []

for img2 in images:
    names.append(img2.object_name)

print(random.choice([names]))

Try this, the problem may that your names was not list varible

If you want to choose one of the file names, try this :

minio = Minio('myip',
                access_key='mykey',
                secret_key='mykey',
              )

images = minio.list_objects('mybucket', recursive=True)

names = []
for img2 in images:
    names.append(img2.object_name)

print(random.choice(names))

The first code tries to randomly select a value from the array, [names], but this only contain a single value, the value of the names variable after the last iteration of the for loop. Instead of doing that, create an array, names and append the values of img2.object_name from each iteration of the for loop to this array. And use this array to get the random name.

Your names is just a simple variable that contains the most recently seen image name, rather than a list full of them.

The very last line of your script works as the one below:

value = 2
print(random.choice([value]))

which always prints 2. To get what you want, you need a list of all images. Here is your code with a simple fix:

names = []
for img2 in images:
    names.append(img2.object_name)

print(random.choice(names))

These code can be made considerably shorter with list comprehension:

names = [img2.object_name for img2 in images]
print(random.choice([names]))
Related