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

Is there a way to simplify this? Make 'x' amount of lists & append 'x' amount of random numbers

For context:
I need to make 20 lists (eg. qlist_20) and append 20 random numbers to each list. The code I have written below works, but I would like to see ideas on how to reduce code, potentially make it a one liner?

for i in range(1, 21):
  list_mkr = ""
  list_mkr = "qlist_" + str(i) + "= []"
  exec(list_mkr)
  for x in range (1, 21):
    n = random.randint(0,100)
    list_app = ""
    list_app = "qlist_" + str(i) + ".append(n)"
    exec(list_app)

>Solution :

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

Here is my attempt:

import random

rdict =  {f'qlist_{x}': random.choices(range(0, 101), k=20) for x in range(1, 21)}

print(rdict)

Output:

{'qlist_1': [76, 39, 14, 44, 35, 73, 25, 74, 39, 97, 97, 52, 33, 55, 90, 91, 16, 10, 16, 22], 
'qlist_2': [19, 69, 97, 37, 43, 37, 80, 77, 58, 18, 55, 9, 68, 6, 55, 81, 38, 86, 61, 24], 
'qlist_3': [39, 89, 7, 61, 66, 19, 80, 11, 59, 45, 61, 32, 39, 23, 11, 39, 33, 20, 51, 35], 
'qlist_4': [8, 17, 34, 7, 54, 31, 42, 69, 43, 71, 97, 20, 63, 24, 73, 30, 55, 43, 2, 87], 
'qlist_5': [65, 58, 56, 64, 57, 9, 94, 23, 38, 6, 12, 65, 67, 54, 73, 18, 4, 88, 2, 6], 
.....}

Recent edit was suggested by @buran in comments

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