python - 随机更改列表值的一半
问题描述
我正在处理 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]]
很好,但是,我想要一些可以随机隐藏一半值的东西?有任何想法吗?
解决方案
试试这个
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)
这个我没试过。但我认为这会如你所愿。
推荐阅读
- c++ - 在 C++ 中旋转 PNG 图像
- java - 如何遍历数组列表并将符合条件的某些对象复制到另一个数组列表?
- ruby-on-rails - 迁移:将整数更改为引用而不丢失行
- ios - UICollectionView 单元格没有出现
- javascript - 将加载回复添加到现有的发布系统
- python - 无法对我的数据应用 scipy.signal lfilter
- c# - 特定对象的统一相机缩放(2D)
- c - 程序在字符串列表中查找重复字符串
- javascript - 如何在本地测试firebase onCall()?
- ios - 如何使用 Swift 4.2 在我的 WebView 中更改用户代理?