Home > Mobile >  Is there a way to simplify this? Make 'x' amount of lists & append 'x' amount of
Is there a way to simplify this? Make 'x' amount of lists & append 'x' amount of

Time:07-01

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)

CodePudding user response:

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

CodePudding user response:

Another possible solution:

from random import randint

def random_square_matrix(n):
    return [[randint(0,100) for i in range(n)] for j in range(n)]

Examples:

>>> random_square_matrix(4)
[[79, 68, 93, 10], [82, 2, 25, 38], [72, 54, 41, 64], [21, 18, 17, 15]]

>>> m = random_square_matrix(2)

>>> m
[[84, 58], [83, 80]]

>>> m[0]
[84, 58]

>>> m[1]
[83, 80]
  • Related