Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中随机生成2D列表_Python_List_Function - Fatal编程技术网

在Python中随机生成2D列表

在Python中随机生成2D列表,python,list,function,Python,List,Function,我正在尝试生成5x5列表,其中正好有10个放置在2D列表中的随机位置 我想让剩下的条目为零。我怎样才能做到 import random def randomNumbers(): mylist=[random.randint(0, 1) for _ in range(5)] return mylist 你可以这样做 来自随机导入洗牌 def random numbers(): l=[1代表范围内(10)]+[0代表范围内(15)] 洗牌(l) lst=[] 对于范围(0,25

我正在尝试生成5x5列表,其中正好有10个放置在2D列表中的随机位置

我想让剩下的条目为零。我怎样才能做到

import random

def randomNumbers():

    mylist=[random.randint(0, 1) for _ in range(5)]
    return mylist
你可以这样做

来自随机导入洗牌
def random numbers():
l=[1代表范围内(10)]+[0代表范围内(15)]
洗牌(l)
lst=[]
对于范围(0,25,5)内的i:
第一个附加(l[i:i+5])
返回lst

一种方法是从一个充满零的二维列表开始,然后选择十个不同的坐标插入一个:

from random import sample

width = 5
height = 5
sample_size = 10

assert sample_size <= width * height

matrix = [[0] * width for _ in range(height)]

for x, y in sample([(x, y) for x in range(width) for y in range(height)], k=sample_size):
    matrix[y][x] = 1

for row in matrix:
    print(row)
也许可以试试这个(使用NumPy):

  • 创建一个零的nxn矩阵
  • 当该矩阵之和>10时,继续随机选择2个索引,并将该值设置为1

  • 对于矩阵工作,通常首选的解决方案是numpy。Numpy的数组数据类型比2D列表灵活得多。 但是,这里有一个可能的解决方案,仅使用Python列表:

    
    import random
    
    li = [[0] * 5 for _ in range(5)]  # make 2D list of zeros
    inds = random.sample(range(25), 10)  # get 10 random linear indices
    for ind in inds:
        i, j = ind // 5, ind % 5  # convert the linear indices to 2D
        li[i][j] = 1
    
    
    

    这是嵌套循环的算法,但我没有将矩阵保存在列表中,您可以自己尝试

    import random
    
    for val in range(10):
        for val1 in range(10):
            print(random.randint(0, 1), end=' ')
        print("\n")
    

    另一种使用
    numpy
    的解决方案如下:

    import numpy as np
    import random
    
    N = 5
    ones_N = 10
    x = np.zeros((N,N))
    indices = random.sample(range(N*N), ones_N)
    x.ravel()[indices] = 1
    
    将二维数组转换为一维数组,然后将位置
    索引处的值设置为1

    索引将是从
    范围(N*N)
    中采样的值的
    元素数组

    另一种选择是只洗牌包含
    one
    1的2D数组

    import numpy as np
    N = 5
    ones_N = 10
    x = np.zeros((N,N))
    x.ravel()[:ones_N] = 1
    np.random.shuffle(x.ravel())
    
    这应该起作用:

    import numpy as np
    
    shape_1d = 5
    shape_2d = 5
    number_element = shape_1d * shape_2d
    number_of_ones = 10
    xx = np.zeros((number_element,1))
    idx = np.random.choice(number_element, number_of_ones)
    xx[idx] = 1
    xx = xx.reshape((shape_1d, shape_2d))
    xx = xx.tolist()
    

    首先使用
    random创建一个包含0和1的1D列表。sample
    随机分配1,而不必两次选取相同的索引:

    from random import sample
    
    pos_of_ones = sample(range(25), 10)
    list_1D = [1 if i in pos_of_ones else 0 for i in range(25)]
    
    然后,要制作此2D,有两种选择:

    • 使用Numpy(推荐):
    • 仅使用列表:
    import random
    
    for val in range(10):
        for val1 in range(10):
            print(random.randint(0, 1), end=' ')
        print("\n")
    
    import numpy as np
    import random
    
    N = 5
    ones_N = 10
    x = np.zeros((N,N))
    indices = random.sample(range(N*N), ones_N)
    x.ravel()[indices] = 1
    
    import numpy as np
    N = 5
    ones_N = 10
    x = np.zeros((N,N))
    x.ravel()[:ones_N] = 1
    np.random.shuffle(x.ravel())
    
    import numpy as np
    
    shape_1d = 5
    shape_2d = 5
    number_element = shape_1d * shape_2d
    number_of_ones = 10
    xx = np.zeros((number_element,1))
    idx = np.random.choice(number_element, number_of_ones)
    xx[idx] = 1
    xx = xx.reshape((shape_1d, shape_2d))
    xx = xx.tolist()
    
    from random import sample
    
    pos_of_ones = sample(range(25), 10)
    list_1D = [1 if i in pos_of_ones else 0 for i in range(25)]
    
    result = np.array(list_1D).reshape(5, 5)
    
    result = []
    for i in range(0, 25, 5):
        result.append(list_1D[i:i+5])