Home > Net >  Random selection of list elements
Random selection of list elements

Time:11-20

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.

CodePudding user response:

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.

CodePudding user response:

I had many different errors, when attempting to place this in either a dictionary or as a list-comprehension.

Minimal Code Answer:

import random

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

selection = sorted(random.sample(BENEFITS, random.randint(1, len(BENEFITS))))
print(selection)
  • Related