[英]Print an ordered dict info at specific lines in python
我目前遇到的問題是,我想使用一種格式來打印自己為字典存儲的值,該格式將使游戲中的玩家易於閱讀。 這樣,很容易解釋正在發生的事情。
我搜索了最后一陣子,但找不到我想要的解決方案。 我發現相似的東西卻沒有滿足我的需求。 我認為我在搜索錯誤的術語,因為我仍然在編程時不知所措。
pprint似乎可以解決問題,但文檔對我來說很難破譯。 我也嘗試過使用for循環和while循環來達到我想要的效果,但是我無法正確地通過我的命令來迭代所需的效果。
import collections
def generateBoard():
board = {(x,y):'W' for y in range(1,11) for x in range(1,11)}
oboard = collections.OrderedDict(sorted(board.items()))
return oboard
def printBoard(board):
for x, y in board.items():
return y
board1 = generateBoard()
printBoard(board1)
當前,它將要做的就是像這樣一遍又一遍地打印出“ W”。
'W'
'W'
'W'
我希望這樣打印出來。
'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W'
'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W'
'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W' 'W'
同樣,我嘗試了幾種不同的循環方法,但無法弄清楚如何將數據連接在一起。 另外,因為我對字典進行排序,所以它將以我想要的順序打印出key:data,而不是我想要的格式。
def printBoard(board):
while True:
z = 0
while x <11:
p = 0
z + 1
while p < 11:
if board[x,y] == 'W':
print y.join(x)
p + 1
這是我嘗試過的方法之一,但失敗了。 它不會讓我對我有點了解的if語句使用迭代器,但是我無法想到讓它通過x,y元組以一種不錯的格式打印數據的方法。
編輯:
我同意tr33hous也建議使用類和grc的示例。 這段代碼根據需要存儲值,而且我也可以輕松地調用print函數。 我也只采用了我在該位置輸入的字符串的第一個字符。 這樣一來,我可以將損壞的+船名串聯起來,它仍然會以非常簡潔的方式打印出電路板。
class Board(object):
'''Creates a board object with a print board method.'''
def __init__(self, sides=11):
self.sides = sides
self.storedBoard = {(x,y):'W' for y in range(1,self.sides) for x in range(1,self.sides)}
def print_board(self):
printableBoard = collections.OrderedDict(sorted(self.storedBoard.items()))
for y in range(1, self.sides):
print ' '.join(str(printableBoard[x, y])[0] for x in range(1, self.sides))
我仍然不知道我將如何完全實施船舶損壞或如何對其進行跟蹤,但是我認為這是一個不錯的開始。 現在,盡管這使我可以放置板,然后我可以運行我的船舶布置腳本,並且它將“ W”值更改為船舶描述。
您是否正在尋找這樣的東西?
for y in range(1, 11):
print ' '.join(board[x, y] for x in range(1, 11))
這是僅使用for循環的簡單方法:
for y in range(1, 11):
for x in range(1, 11):
# print the value followed by a single space
print board[x, y],
# print a new line
print
我建議對此類使用類。 我已經重新實現了您的代碼以反映更改:
import collections
class Board(object):
def __init__(self, sides=11):
self.sides = sides
u_board = {(x,y):'W' for y in range(1,self.sides) for x in
range(1,self.sides)}
self.board = collections.OrderedDict(sorted(u_board.items()))
def print_board(self):
for y in range(1, self.sides):
print ' '.join(self.board[x, y] for x in range(1, self.sides))
# Usage
b = Board()
b.print_board()
輸出:
$ python board.py
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
W W W W W W W W W W
編輯修改的打印功能以使用@grc的方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.