How to generate array of size M that only contains elements from provided list?

Question:

What am I trying to achieve?

  • I am trying to generate array of size M, but elements of that array can only be ones that can be find within of provided list.

My Python code:

import random
def generisanjevol1(nekalista):
 return random.choice(nekalista)


listaslova=['A','B','C','D','E']

for x in range(4):
 lista=[generisanjevol1(listaslova)]

print(lista)

Output:

['E']

As shown, in the output that I am getting there’s only one element and not 4 (I expected to be 4, because of for loop)

Example of wanted Output:

['B', 'E', 'A', 'C']

Deeper explanation of what I am trying to achieve:

I have 1 array of 5 strings and I am trying to pass that array into function (generisanjevol1) and there I should generate array of size M (generated by random.choice() function but that array should be generated only from these 5 strings which are in array (listaslova) )
Can anyone help me how to do that exactly and how can I save multiple ‘data’ into one array ?
Thanks

Asked By: str1ng

||

Answers:

If I understand you correctly, you want to generate array of size M that has elements only from supplied list. You can use random.choices() with k= parameter:

import random

M = 4

def generisanjevol1(nekalista, m):
    return random.choices(nekalista, k=m)

listaslova=['A','B','C','D','E']

lista=generisanjevol1(listaslova, M)
print(lista)

Prints (for example):

['A', 'E', 'C', 'E']
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.