【问题标题】:Returning all "positions" of a list返回列表的所有“位置”
【发布时间】:2011-01-18 02:22:31
【问题描述】:

我有一个包含“a”和“b”的列表,“b”有点像路径,“a”是墙壁。我正在编写一个程序来制作所有可能动作的图表。我运行代码来检查第一个“b”是否有可能的移动,但我不知道我将如何找到所有“b”,更不用说不重复检查它们了。

我遇到的主要问题是将“b”的元组坐标从列表中移出。

任何指针/提示?

【问题讨论】:

  • 这个问题缺少一些我认为的重要细节。
  • 最好有一个示例输入和一些您目前掌握的代码。
  • 短篇小说:我想创建一个包含表示字母“b”在列表中的位置的元组的列表。
  • 我认为这是一个二维列表,因为您需要元组坐标? [['b','a','b'],['b','b','b'],['a','a','a']] 之类的东西?
  • 就是这样。关于如何做的任何指示?

标签: python list dictionary graph logic


【解决方案1】:
grid = [['b','a','b'],['b','b','b'],['a','a','a']
results = []
for row in range(len(grid)):
  for col in range(len(grid[row])):
    if grid[row][col] == 'b':
      results.append((row, col))

print results

使用地图可能有更好的方法,但自从我使用 Python 以来已经有一段时间了。

【讨论】:

    【解决方案2】:

    +1 给 Nemo157 的答案。如果您想要完全相同的代码,但在一行中,可以按如下方式完成:

    grid = [['b','a','b'],['b','b','b'],['a','a','a']
    [(row, col) for row in range(len(grid)) for col in range(len(grid[row])) if grid[row][col] == 'b']
    

    干杯!

    【讨论】:

      【解决方案3】:

      这会找到每个方格的有效移动列表。

      我假设地图的边缘是一堵“墙”,你不能沿对角线移动:

      # reference like this: maze[y][x] or maze[row][col]
      # with [0][0] starting at the top left
      maze = [['b','a','a', 'a'],
              ['b','a','b', 'a'],
              ['b','a','b', 'b'],
              ['b','b','b', 'a'],
              ['b','a','b', 'a'],
              ['a','a','a', 'a']]
      
      moves = {}
      
      # Loop through all cells of the maze, starting in the top-left
      for y, row in enumerate(maze):
          for x, value in enumerate(row):
      #        print "y, x, val: ", y, x, value
              # for every cell, create an empty list of moves
              moves[y, x] = []
              # then if we can move from this cell
              # check each of its neighbours and if they are a 'b' add it 
              # to the list of moves - assumes we can't move diagonally
              if value == 'b':
                  if y - 1 > 0 and maze[y - 1][x] == 'b':
                      moves[y, x].append((y - 1, x))
                  if y + 1 < len(maze) and maze[y + 1][x] == 'b':
                      moves[y, x].append((y + 1, x))
                  if x - 1 > 0 and maze[y][x - 1] == 'b':
                      moves[y, x].append((y, x - 1))
                  if x + 1 < len(row) and maze[y][x+1] == 'b':
                      moves[y, x].append((y, x+1))
      
      print moves
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-12
        • 1970-01-01
        • 2017-03-13
        • 2023-03-28
        • 1970-01-01
        相关资源
        最近更新 更多