Home > Back-end >  Repeat a line of code without writing it again
Repeat a line of code without writing it again

Time:09-21

      import random
     a = [[random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)],
         [random.randint(1, 1000) for i in range(0, 10)]]

     for i in a:
    for c in i:
        print(c, end = " ")
    print()

that is just a part if my programm. I need 10x10 random generated numbers. Is there a way to write/formate it better. Maybe in less lines.

Thank you in advance.

CodePudding user response:

You can do a double list comprehension:

a = [[random.randint(1, 1000) for _ in range(0, 10)] for _ in range(0, 10)]

CodePudding user response:

Just use another loop outside the one building the inner loops:

a = [[random.randint(1, 1000) for i in range(10)] for _ in range(10)]

Or use random.choices to save on using the inner loop:

a = [random.choices(range(1, 1001), k=10) for _ in range(10)]

CodePudding user response:

The following should fulfill your requirements

for i in range(10):
    print([random.randint(1, 1000) for j in range(10)])

CodePudding user response:

I already hinted at double list comprehension in my comment, but anyway:

import random
a = [random.choices(range(1, 1001), k=10) for _ in range(10)] # range will not include 1000, while randint will, so it has to be range(1001)

If you want unique elements (per sublist), you can use random.sample() instead of random.choices()

  • Related