需要帮助替换列表中的项目

时间:2014-10-05 20:06:10

标签: python python-3.x

我在不同位置创建了python蜜蜂,降雨和树木的程序,我希望蜜蜂能够移动。但是,当我运行我的程序时,它总是因类型错误而卡住。有人可以向我解释导致问题的原因以及如何解决问题。此外,我是一个完整的编程初学者,因此任何有关如何使我的代码更快或更合理的提示都会很乐意接受。该计划的代码如下:

import random


wb0,wb1,wb2,wb3,wb4,wb5,wb6,wb7,wb8,wb9 = [],[],[],[],[],[],[],[],[],[]

worker_bees = [wb0,wb1,wb2,wb3,wb4,wb5,wb6,wb7,wb8,wb9]


f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14 = [],[],[],[],[],[],[],[],[],[],[],[],[],[],[]

flowers = [f0,f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14]


t0,t1,t2,t3,t4 = [],[],[],[],[]

trees = [t0,t1,t2,t3,t4]


def world_generate():


    def worker_bee_spawn():

        x = 0
        i = 0

        while i < 10:

            worker_bees[x] = (random.randrange(0,100), random.randrange(0,100))

            x += 1
            i += 1


    def flower_spawn():

        x = 0
        i = 0

        while i < 15:

            flowers[x] = (random.randrange(0,100), random.randrange(0,100))

            x += 1
            i += 1

            if flowers[x - 1] == worker_bees:
                x -= 1
                i -= 1


    def tree_spawn():

        x = 0
        i = 0

        while i < 5:

            trees[x] = (random.randrange(0,100), random.randrange(0,100))

            x += 1
            i += 1

            if trees[x - 1] == worker_bees:
                x -= 1
                i -= 1

            elif trees[x - 1] == flowers:
                x -= 1
                i -= 1


    worker_bee_spawn()

    flower_spawn()

    tree_spawn()


world_generate()


def worker_bee_movement():

        x = 0
        i = 0

        while i < 10:

            worker_bee = worker_bees[x]

            worker_bee_x = worker_bee[0]

            worker_bee_x += 1

            worker_bee[0] = worker_bee_x

            worker_bees_x = worker_bee  


            x += 1
            i += 1



worker_bee_movement()

1 个答案:

答案 0 :(得分:1)

更改以下行:

 while i < 10:
      worker_bee = list(worker_bees[x])

worker_bees[x]是一个元组,因此worker_bee = worker_bees[x]然后将worker_bee设为元组,而worker_bee[0] = worker_bee_x将失败:

  'tuple' object does not support item assignment

要说清楚,(1,2,3)[0] = 3是不允许的,[1,2,3][0] = 3是允许的

使用range创建列表列表

worker_bees = [[] for _ in range(10)]


flowers = [[] for _ in range(15)]


trees = [[] for _ in range(4)]