Python 嵌套字典 "None" 迭代完成后出现
Python Nested Dictionary "None" coming up when it's done iterating
我正在使用 Python 将无聊的东西自动化,我很困惑为什么“None”在字典中完成迭代后会不断出现。我正在数一数有多少个棋子。我知道我目前只是在计算空间。
原来我有。
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
提前致谢,
函数中有一个打印,然后函数的 RETURN 有打印。函数没有返回任何内容,所以第二个 print 语句什么也没有打印!很接近。这对我来说更有意义。
chessPieces = { 'player1': {'1a': 'wpawn', '1b': 'wknight', '1c': 'wbishop'},
'player2': {'8a': 'bpawn', '8b': 'bknight', '8c': 'bbishop'}}
def CountChessPieces(d):
numPieces = 0
for k in d.keys():
for v in d[k].keys():
numPieces += 1
return numPieces
print(CountChessPieces(chessPieces))
我正在使用 Python 将无聊的东西自动化,我很困惑为什么“None”在字典中完成迭代后会不断出现。我正在数一数有多少个棋子。我知道我目前只是在计算空间。
原来我有。
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
提前致谢,
函数中有一个打印,然后函数的 RETURN 有打印。函数没有返回任何内容,所以第二个 print 语句什么也没有打印!很接近。这对我来说更有意义。
chessPieces = { 'player1': {'1a': 'wpawn', '1b': 'wknight', '1c': 'wbishop'},
'player2': {'8a': 'bpawn', '8b': 'bknight', '8c': 'bbishop'}}
def CountChessPieces(d):
numPieces = 0
for k in d.keys():
for v in d[k].keys():
numPieces += 1
return numPieces
print(CountChessPieces(chessPieces))