【问题标题】:Python Nested Dictionary "None" coming up when it's done iteratingPython嵌套字典“无”在完成迭代时出现
【发布时间】: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


【解决方案1】:

你在函数中有一个 print,然后你有 print 用于函数的 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))

【讨论】:

  • 我现在觉得很傻,哈哈。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 2021-11-29
相关资源
最近更新 更多