vendredi 19 novembre 2021

Random selection of list elements

Goal: print random selection of list elements, at least 1 to all, as a list-comprehension.

Attempt:

import random

BENEFITS = ['foo', 'bar', 'idk', 'lol']

selection = [sorted(random.sample(BENEFITS, random.randint(1, len(BENEFITS))]
print(selection)

Desired Output:

foo, idk

ValueError:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-17-407cc8d7fbfe> in <module>
----> 1 v = [[k, eval(v)] for k, v in sorted(random.sample([BENEFITS], random.randint(3, len(BENEFITS)-1)))]
      2 
      3 print(v)

~\Anaconda3\lib\random.py in sample(self, population, k)
    361         n = len(population)
    362         if not 0 <= k <= n:
--> 363             raise ValueError("Sample larger than population or is negative")
    364         result = [None] * k
    365         setsize = 21        # size of a small set minus size of an empty list

ValueError: Sample larger than population or is negative

Please let me know if there is anything else I can add to post.




Aucun commentaire:

Enregistrer un commentaire