随机将列表中的项目附加到矩阵列表中

时间:2011-12-05 19:13:10

标签: python

我正在尝试制作游戏。我有一份清单。我想获取此列表中的项目并随机将它们附加到列表矩阵中的索引。想想一个网格和一个项目随机移动通过这个网格。

import random


fishlist = ["salmon", "carp", "bass", "catfish"]


grid = [
            [1,2,3],
            [4,5,6],
            [7,8,9],
            ]

我想用随机鱼替换每个数字。从那里我希望鱼能够在网格中移动。最好的方法是什么?谢谢您的帮助。

2 个答案:

答案 0 :(得分:3)

试试这个

>>> grid = [
            [1,2,3],
            [4,5,6],
            [7,8,9],
            ]
>>> fishlist = ["salmon", "carp", "bass", "catfish"]

>>> [r.__setitem__(i,random.choice(fishlist)) for r in grid for i in xrange(0,len(r))]
[None, None, None, None, None, None, None, None, None]
>>> print grid
[['salmon', 'salmon', 'carp'], ['carp', 'salmon', 'bass'], ['bass', 'salmon', 'bass']]
>>> 

移动鱼试试这个

>>> def Move(grid):
    rSrc=random.choice(grid)
    rDest=random.choice(grid)
    a,b=random.randint(0,len(rSrc)-1),random.randint(0,len(rSrc)-1)
    rSrc[a],rDest[b]=rDest[b],rSrc[a]
    >>> grid
[['carp', 'catfish', 'catfish'], ['catfish', 'carp', 'salmon'], ['catfish', 'catfish', 'carp']]
>>> Move(grid)
>>> grid
[['catfish', 'catfish', 'carp'], ['catfish', 'carp', 'salmon'], ['catfish', 'catfish', 'carp']]
>>> 

使用循环

>>> grid = [
            [1,2,3],
            [4,5,6],
            [7,8,9],
            ]
>>> fishlist = ["salmon", "carp", "bass", "catfish"]
>>> for r in grid:
    for i in xrange(0,len(r)):
        r[i]=random.choice(fishlist)


>>> grid
[['bass', 'catfish', 'carp'], ['catfish', 'salmon', 'salmon'], ['bass', 'salmon', 'catfish']]
>>> 

答案 1 :(得分:0)

您可以创建一个包含从index到fish

的映射的列表
import random  
random.seed()  # init the random seed
fish = [0] * 11   # init the array  
for i in range(1,11):     #for each indexes from 1 to 10
    fish[i] = random.choice(fishlist)

然后,对于每个网格

grid_fish = [[0,0,0],[0,0,0,],[0,0,0]] #init the fish grid

for i in range(0,len(grid):
   for j in range(0,len(grid[i])):
       grid_fish[i][j] = fish[ grid[i][j] ]     

对于网格中的每个项目,根据数组fish中的索引获取fish的名称,并将结果放入grid_fish