【问题标题】:How to print a 2D list so that each list is on a new line with a space, without any "" or []如何打印 2D 列表,使每个列表都在一个带有空格的新行上,没有任何“”或 []
【发布时间】:2017-11-30 20:45:24
【问题描述】:

我无法在具有视觉吸引力的庄园中打印列表。 列表的一个例子是

[["-", "-", "-", "-"],["-", "-", "-", "-"],["-", "-", "-", "-"]] 

(字符不一定都相同),但我需要在不使用除printrangeleninsertappendpop 之外的任何函数的情况下打印它,并且我不能使用任何字典或地图,或导入任何库或使用任何列表理解。我反过来想要:

- - - -
- - - - 
- - - - 

我试过了:

def print_board(board): 
    for i in board: 
        row = board[i] 
        for r in row: 
            print(*row[r], "\n")

【问题讨论】:

  • print 是否允许?
  • 到目前为止你做了什么?
  • " 我需要在不使用除 range、len、insert、append、pop 之外的任何函数的情况下打印它:这正是您应该做的事情一个好的python代码...
  • 因为你不被允许使用print() 函数,你会玩这个很糟糕的。
  • psst... 您的示例列表缺少一些逗号。

标签: python arrays list printing


【解决方案1】:

您很接近,但您误解了for i in <list> 的工作原理。迭代变量获取列表元素,而不是它们的索引。

另外,row[r](如果 r 是索引)将只是一个字符串,而不是一个列表,因此您不需要使用 *row[r] 解压缩它。

没有必要在 print() 调用中包含 "\n",因为它默认以换行符结束输出 - 您必须使用 end="" 选项覆盖它以防止它。

for row in board:
    for col in row:
        print(col, end=" ") # print each element separated by space
    print() # Add newline

【讨论】:

    【解决方案2】:
    board = [["-", "-", "-", "-"],["-", "-", "-", "-"],["-", "-", "-", "-"]] 
    
    for row in board:
        print(*row)
    

    这是最简单的方法,但依赖于参数解包(*row 之前的星号)。如果由于某种原因您不能使用它,那么您可以使用 print 的关键字参数来获得相同的结果

    for row in board:
        for cell in row:
            print(cell, end=' ')
        print()
    

    【讨论】:

      【解决方案3】:

      使用更好的命名变量可能会导致更好的理解:

      def print_board(board): 
          for innerList in board: 
              for elem in innerList: 
                  print(elem + " ", end ='') # no \n after print
              print("") # now \n
      
      
      b = [["-"]*4]*4       
      print_board(b)
      print(b)
      

      输出:

      - - - -  
      - - - -  
      - - - -  
      - - - -  
      
      [['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-'], ['-', '-', '-', '-']]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-13
        • 1970-01-01
        • 2020-11-10
        • 2019-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多