我试图创建一个功能,告诉用户他们所在房间的出口。每个子列表都是一个房间。所有非零数字都是我的二维列表中每个子列表的出口。所有零都不是退出。我一直得到输出"当我的地图的第一个值是$this->Auth->user('username');
时,连续4次没有退出到0号房间" 它显然有2和3哪个有出口。我想知道我做错了什么?
[0, 2, 3, 0]
答案 0 :(得分:0)
删除elif条件并使用else,因为没有其他可能的答案。除此之外
map=[[0, 2, 3, 0], [0, 0, 4, 1], [1, 4, 0, 0], [2, 0, 0, 3], [0, 2, 3, 0], [0, 0, 4, 1], [1, 4, 0, 0], [2, 0, 0, 3], [0, 2, 3, 0], [0, 0, 4, 1], [1, 4, 0, 0], [2, 0, 0, 3], [0, 2, 3, 0], [0, 0, 4, 1], [1, 4, 0, 0], [2, 0, 0, 3]]
class Player:
def __init__(self, room_number = 0):
self.room_number = room_number
def exit_count(self):
for n in range(0,4):
# print n
# print map[self.room_number][n]
if map[self.room_number][n] == 0:
print("There is no exit to room {0}\n".format(self.room_number))
else:
print("There is an exit to room {0}\n".format(self.room_number))
p = Player(room_number=4)
p.exit_count()
奏
There is no exit to room 4
There is an exit to room 4
There is an exit to room 4
There is no exit to room 4
[Finished in 0.0s]
答案 1 :(得分:0)
只需使用以下
即可def findexits(rooms):
for room in rooms:
yield [door for door in room if door]
exits = findexits(map) # this is a generator
# list(exits) => [[2,3], [..],...]
# If you wish to calculate the number of exits, employ the generator
# before consuming
exit_counts = [len(exit_) for exit_ in exits]
# this consumes it.
您可以通过各种方式修改findexits
。