Home > front end >  (Python) How to pull random elements from a list according to user input?
(Python) How to pull random elements from a list according to user input?

Time:10-30

I'm writing a program which will create 4 lists with words in them. A user is prompted to answer how many words they'd like to print from list A, how many from list B, how many from list C, D etc. and the program randomly chooses those words and prints them out.

I've got the shell out ready, the lists are made up, and the user input prompts are done, I can't figure out how to connect these two together. I can print out random values from a list using random.choice() but the amount that I specify. Not the number of words the user specifies.

CodePudding user response:

You could define one variable that come from the user, let say "x", this variable take the value:

hmf=[] #this is the list that in each spaces the number of selection random words

for j in (0,4):
  x=int(input())
  hmf.append(x)

In that case you have:

# hmf[0] = numbers of words from the list A
# hmf[1] = numbers of words from the list B
# hmf[2] = numbers of words from the list C
# hmf[3] = numbers of words from the list D

CodePudding user response:

Python has the built-in module random that contains a function known as choice which randomly selects an element from a list. Import it using the following.

from random import choice

x is that list containing the words. n is how much you want the new list elements be. acc is an accumulator. How this function works is that we select a random element from the list, add it to the accumulator and re-call the function with decrement of n till it reaches 0, were we return the accumulator.

cr_list = lambda x, n, acc: acc if n == 0 else cr_list(x, n-1, acc   [choice(x)])

Here's an example of the function.

data_base = ['a', 'b', 'c', 'd']
print(cr_list(data_base, 4, []))
  • Related