vendredi 12 mars 2021

Randomly select an element from a list, but the lower an element is, the more chance it has to be selected

I want to randomly select an item from a list. But the twist is that the higher index an element in the list possesses, the most likely it will be chosen. And after randomly choosing an item in the list, I would like to store that item into a variable named link.

I haven't tried a lot of different ways, since I don't know where to start. But this is what I currently have:

import random

# A list of Youtube links ( I won't show the YT links )
links = ['link1 :D',
         'link2 :D',
         'link3 :D'
]

link = random.choice(links)

With the code above, I only get a random ( or pseudorandom ) result from an item in the links variable. How can I write the code so that it has a higher of choosing ( but still randomly ) the items with a larger index?

In case I'm not being clear, here is an example:

# List of 3 links

links = ['link1', # index: 0
'link2', # index: 1
'link3' # index: 2]

Since link3 has the highest index of 2, it has the highest possibility of being selected by a random selector. link2 has the second-highest index, so it has more chances of being selected than link1, but fewer chances of being selected than link3.




Aucun commentaire:

Enregistrer un commentaire