【问题标题】:Pick multiple index of a specific list of list选择特定列表列表的多个索引
【发布时间】:2019-06-05 15:44:56
【问题描述】:

向阅读本文的人致敬! 我被分配在 python 中制作一个扫雷程序,是的,我可以复制粘贴一个已经制作好的扫雷程序,但我想自己制作,但我在这里的列表很难。 为了让事情更清楚一点,我有主列表让我们在其中称之为列表我还有 10 个用于游戏板行的列表但是 现在我必须将地雷添加到其中,我找不到将它们随机放置在列表周围的方法!

x=random.choice(list)
    board.replace(x,"nuke",forrow)
-----------------------------------------
x=randrange(len(list))
    board.replace(x,"nuke",forrow)
--------------------------------------
x=random.sample(list[i],1)
    board.insert(x,"nuke")
----------------------------------------
    for x in range(len(list)):
            board.insert(random.choice(x),"nuke")

import random
board = [[" "]*10 for i in range(10)]# here i create the big list and the other ones within it

bombs=15#input("Please provide the amount of bombs you want in the game: ")

for list in board: #here is my problem
    x=random.sample(list[i],1) 
    board.insert(x,"nuke")



for x in board:print x 

我期待任何能够帮助我完成我的小程序的东西 我需要一些东西才能获得列表中 X 个位置的位置,并能够用“炸弹”替换它们,所以就这么称呼吧!

【问题讨论】:

  • 不要使用列表作为变量名。另外你对这条线有什么期待? x = random.sample(list_[i], 1)
  • 使用random.sample(或random.choice),您将从列表中获取一个元素,而不是随机索引。请改用randrange。此外,insert添加一个“nuke”,而不是将一个单元格更改为一个 nuke。
  • list_=['a','b','c','d'] 我想要的是从 list_ 2 randoms f.e. 'b' ,'d' 但不是他们我想要的位置 list_[1] list_[2] 当我到达那里的位置时用其他东西替换它们(我希望我帮助你:/)

标签: python python-2.7 list random minesweeper


【解决方案1】:

这种方法不是在现场随机选择位置,而是:用适量的“核武器”和空单元格初始化一个长列表,random.shuffle 该列表,并将其分解为二维板。

>>> bombs = 15
>>> all_cells = ["nuke"] * bombs + [" "] * (100 - bombs)
>>> random.shuffle(all_cells)
>>> board = [all_cells[i:i+10] for i in range(0, 100, 10)]

这样,您不必检查之前是否已经随机滚动了相同的单元格。

【讨论】:

    猜你喜欢
    • 2019-10-26
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多