【发布时间】:2021-10-21 17:19:54
【问题描述】:
我正在用 Python 自动化无聊的东西,我很困惑为什么“无”在遍历字典后会不断出现。我想数一数有多少棋子。我知道我目前只计算空间。
原来我有。
chessPieces = { 'player1': {'1a': 'wpawn', '1b': 'wknight', '1c': 'wbishop'},
'player2': {'8a': 'bpawn', '8b': 'bknight', '8c': 'bbishop'}}
def isValidChessBoard(d):
numPieces = 0
for k in d.keys():
for v in d[k].keys():
numPieces += 1
print(numPieces)
然后我想也许添加一个while循环来计算键的数量可能有助于避免它,但我得到了相同的结果。知道为什么会发生这种情况,或者我没有正确理解什么吗?
chessPieces = { 'player1': {'1a': 'wpawn', '1b': 'wknight', '1c': 'wbishop'},
'player2': {'8a': 'bpawn', '8b': 'bknight', '8c': 'bbishop'}}
def isValidChessBoard(d):
numPieces = 0
players = len(d.keys())
while players:
for k in d.keys():
players -= 1
for v in d[k].keys():
numPieces += 1
print(numPieces)
print(isValidChessBoard(chessPieces))
Output
6
None
提前致谢,
【问题讨论】:
-
numPieces = sum(map(len, chessPieces.values())).
标签: python dictionary nonetype