【问题标题】:sum() error, unsupported operant type int and nonetypesum() 错误,不支持的操作数类型 int 和 nonetype
【发布时间】:2022-12-05 17:45:44
【问题描述】:

我正在尝试进行代码第 2 天的到来,但当我尝试求和以找到剪刀石头布的总和时遇到错误:


map_input = {'A': 'Rock', 'B': 'Paper', 'C': 'Scissors', 'X': 'Rock', 'Y': 'Paper', 'Z': 'Scissors'}
points_per_shape = {'Rock': 1, 'Paper': 2, 'Scissors': 3}
points_per_outcome = {'Lose': 0, 'Draw': 3, 'Win': 6}



with open(r'C:\Users\my_name\OneDrive\Documents\advent of code\day 2\input.in') as f:
    lines = f.readlines()
    rounds = [entry.strip() for entry in lines]

def points_per_round(round_string):
    opponent_shape = map_input[round_string[0]] #opponent, first character
    our_shape = map_input[round_string[2]] #me, second character

    if opponent_shape == our_shape:
        return points_per_outcome['Draw'] + points_per_shape[our_shape]
    elif (opponent_shape, our_shape) in [('Paper', 'Rock'), ('Rock', 'Scissors'), ('Scissors, Paper')]:
        return points_per_outcome['Lose'] + points_per_shape[our_shape]
    elif (opponent_shape, our_shape) in [('Rock', 'Paper'), ('Scissors', 'Rock'), ('Paper', 'Scissors')]:   
        return points_per_outcome['Win'] + points_per_shape[our_shape]
        
    
total = sum([points_per_round(round_string) for round_string in rounds])
print(total)

有问题的文件是这样的 B X 一个Z 是

像这样继续数千行

当我尝试运行代码时出现此错误,但如果我将最后一行从 elif 替换为 elsee,则不会出现任何错误,但会得到错误的答案

Traceback (most recent call last):
  File "c:\Users\my_name\OneDrive\Documents\advent of code\day 2\rock paper scissors.py", line 23, in <module>
    total = sum([points_per_round(round_string) for round_string in rounds])
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

当我尝试运行代码时出现此错误,但如果我将最后一行从 elif 替换为 elsee,则不会出现任何错误,但会得到错误的答案

【问题讨论】:

  • 在某些情况下,points_per_round()是(隐含地)返回无。您需要调试该功能
  • 如果您的 if/elif 案例都不适用,您的程序将返回 None(NoneType 的实例)。 sum() 使用 + 运算符,它不能将 None 添加到数字。如果所有情况都不适用,您需要指定要做什么。例如,添加else: return 0

标签: python


【解决方案1】:

在第一个elif 中有一个错字:

elif (opponent_shape, our_shape) in [('Paper', 'Rock'), ('Rock', 'Scissors'), ('Scissors, Paper')]

应该

elif (opponent_shape, our_shape) in [('Paper', 'Rock'), ('Rock', 'Scissors'), ('Scissors', 'Paper')]

请注意代码中的最后一个示例是一个元组,它包含一个包含文本Scissors, Paper 的字符串,而它应该是一个包含两个字符串的元组,一个包含文本Scissors,另一个包含文本Paper

【讨论】:

    【解决方案2】:

    你得到这个错误是因为最后一行是空的,所以你可以使用数组的pop()方法来删除lines的最后一行

    【讨论】:

      【解决方案3】:

      总结其他人已经指出的内容:

      1. 你在第一个 elif 语句 ('Scissors, Paper') 而不是 ('Scissors', 'Paper') 中有错字
      2. 如果不满足任何条件,您的if循环可以隐式返回None。这可能是由于您的错字造成的。考虑添加 else 语句以显式返回有用的值或抛出类似 Didn't match any of the conditions 的错误

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-16
        • 2020-08-26
        • 1970-01-01
        • 1970-01-01
        • 2023-02-12
        • 1970-01-01
        • 2019-08-22
        相关资源
        最近更新 更多