2015-12-14 32 views
1

我有打印出一个网格的战列舰游戏(5'行打印5x),并生成一个随机点供用户猜测。尝试打印行号时输入错误

这些都是行:16-20

""" Allows the function to print row by row """ 
    def print_board(board): 
     for row in board: 
      for x in enumerate(row): 
       print('%s " ".join(row)' % (x)) 

我得到这些错误。但是,只是后我改变线20来打印印格旁边的数量(http://imgur.com/uRyMeLU)图片有

Traceback (most recent call last): File "C:\Users\Jarrall\pythonPrac\battleship.py", line 23, in <module> 
    print_board(board) File "C:\Users\Jarrall\pythonPrac\battleship.py", line 20, in print_board 
    print('%s " ".join(row)' % (x)) TypeError: not all arguments converted during string formatting 

我怎么会拿到这块代码打印数量(枚举排列表的长度?)旁边的网格?

+0

只是,你的文档字符串应该在*函数内部,在签名之后并且缩进到与最外部的'for'相同的级别。 – jpmc26

回答

0

从您的堆栈跟踪以一种猜测,我会说你需要x变量转换为字符串,像这样:

print('%s " ".join(row)' % (str(x))) 
1

您使用enumerate错误。我不能完全肯定,但像你想它来打印像它看起来对我说:

0 0 0 0 0 0 
1 0 0 0 0 0 
2 0 0 0 0 0 
3 0 0 0 0 0 
4 0 0 0 0 0 

这可以通过enumerate(board)因为enumerate回报指数和迭代器来完成:

def print_board(board): 
    for index,row in enumerate(board): 
     print('{} {}'.format(index, ' '.join(row)) 

使你可以得到:

>>> board = [['0' for _ in range(5)] for __ in range(5)] 
>>> print_board(board) 
0 0 0 0 0 0 
1 0 0 0 0 0 
2 0 0 0 0 0 
3 0 0 0 0 0 
4 0 0 0 0 0 

编辑 - 添加,为什么你的当前print声明需要一些fixin':

您的print声明不符合您的预期。让我们通过它:

print('%s " ".join(row)' % (x)) 
    #'    ' will create a string literal. This is obvious. 
    # %s    a string formatting token meaning to replace with a string 
    #     % (x) the replacement for any of the string formatting 
    # " ".join(row) this is your vital flaw. Although this is valid code, the print 
    #     statement will print this as literally `" ".join(row) 
    #     rather than actually running the code. 

这就是为什么你需要将其更改为:

print('{} {}'.format(index, ' '.join(row)) 
#shout-out to jpmc26 for changing this 

这取代的{}format给出的参数的所有实例。您可以了解更多关于与字符串格式有关的迷你语言here

+0

我编写了'print'调用,因为它不兼容Python 2.7(尽管它在Python 3.x中工作)。你可能还想提一下关于与'print'命令不同的地方,因为OP似乎对如何使用字符串格式感到困惑。 – jpmc26

+0

@ jpmc26感谢编辑,我现在正在重新编辑添加解释。意外地点击编辑加载框,而我的编辑中,并失去了我已经有的所有*为什么我必须这样做自己* –

0

Python的枚举方法返回一个包含0索引整数的元组以及列表值。所以,而不是简单地作为行中的值,你的x变量实际上是(整数,行)。如果您只想打印整数列表,请将您的内循环更改为以下内容:

for x,y in enumerate(row): 
    print('%s " ".join(row)' % (x)) 

这应该可以解决您的问题。如果您想要更具体的答案,请详细说明您想要做什么以及行变量是什么。