我正在尝试制作一个战舰网格,数字在左边,字母在上面。我对如何打印出一定数量的字母并使用python添加它们感到困惑。在Python方面,我是一个非常新的初学者。
例如:
def displayGrid(Rows,Columns):
output = '| '
for title in range(97,110):
output = output + chr(title)
output = output + ' |'
print(output)
for row in range(Rows):
output = str(row + 1) + '| '
for col in range(Columns):
output = output + " | "
print(output)
Rows = int(input("Number of rows you want? n"))
Columns = int(input("Number of columns you want? n"))
displayGrid(Rows, Columns)
我想要它,所以列数是它打印出来的字母数,但我似乎无法弄清楚。
您的第一个循环 ( for title in range(97,110):
) 将始终具有固定长度(110-97=13 个元素),因此无论您想要多少列,您都将始终以相同的第一行结束。
尝试类似for title in range(97, 97+Columns):
您可以通过以下方式访问小写字母
from string import lowercase
实现字符串的一个干净方法是:
result = "| " + " | ".join(lowercase[0:size]) + " |"
替换这个
for title in range(97,110):
output = output + chr(title)
output = output + ' |'
print(output)
由
output = " |" +"|".join([chr(i) for i in range(97,97+Columns)])
print(output)
一些提示 -
-
当你有一个可迭代的你想要打印和加入某些分隔符时,你可以使用 join -
'|'.join(["a", "b", "c"]) a|b|c
-
from string import lowercase
会给你一个字符串(你可以迭代)所有的小写字母。 -
检查 python 迭代工具 - https://docs.python.org/2/library/itertools.html