Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly generate 2D list in Python

I am trying to generate 5x5 list that has exactly 10 ones placed in a random locations in the 2D list.

I want to make the rest of the entries is zeroes. How can I make it?

import random

def randomNumbers():

    mylist=[random.randint(0, 1) for _ in range(5)]
    return mylist
like image 905
ds_ds Avatar asked Jan 22 '26 05:01

ds_ds


1 Answers

You can do this

from random import shuffle
def randomNumbers():
    l=[1 for _ in range(10)]+[0 for _ in range(15)]
    shuffle(l)
    lst=[]
    for i in range(0,25,5):
        lst.append(l[i:i+5])
    return lst
like image 92
Shadowcoder Avatar answered Jan 24 '26 18:01

Shadowcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!