Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

You can use choices from module random. Then

from random import choices
BENEFITS = ['foo', 'bar', 'idk', 'lol']
print(choices(BENEFITS,k=2))

At this way, function choices returns a random sample of length k=2 from BENEFITS.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading