首页 > 解决方案 > 随机更改列表值的一半

问题描述

我正在处理 python 上的 2D 列表并尝试从网格中隐藏一些值:

想象这是网格:

[[0, 0, 1, 1], 
[0, 1, 0, 1],
[1, 0, 1, 0],
[1, 1, 0, 0]]

我用这段代码得到的结果:

    def startingArray(self,grid_copy): 
        for i in range (len(grid_copy)):
            n= self.CELL
            if n>len(grid_copy):
                grid_copy[i]=[2 for i in grid_copy]
            else:
                for i in range(n):
                    position=random.randrange(0,len(grid_copy[i]))
                    grid_copy[i][position]= 2  

[[2, 0, 1, 2],
 [2, 2, 2, 1],
 [2, 0, 2, 2],
 [2, 1, 2, 2]]

很好,但是,我想要一些可以随机隐藏一半值的东西?有任何想法吗?

标签: pythonlistrandom

解决方案


试试这个

def startingArray(self,grid_copy): 
    for row in grid_copy:
       prevItems = []
       for i in range(len(row)/2+1):
           if (i not in prevItems):
               row[random.randint(0, len(row) - 1)] = 2
               prevItems.append(i)

这个我没试过。但我认为这会如你所愿。


推荐阅读