Python 属性错误 if 语句

Python Attribute Error if statement

我已经在这段代码上工作了大约一天了。几个小时后,就这一部分,它一直说我在第 26 行有一个属性错误。不幸的是,这就是我所拥有的所有信息。我尝试了无数种不同的方法来修复它并搜索了很多 websites/forums。我感谢任何帮助。这是代码:

import itertools
def answer(x, y, z):
    monthdays = {31,
                 28,
                 31, 
                 30, 
                 31, 
                 30, 
                 31, 
                 31, 
                 30, 
                 31, 
                 30, 
                 31}
    real_outcomes = set()
    MONTH = 0
    DAY = 1
    YEAR = 2

    #perms = [[x, y, z],[x, z, y],[y, z, x],[y, x, z],[z, x, y],[z, y, x]]
    possibilities = itertools.permutations([x, y, z])
    for perm in possibilities:
        month_test = perm[MONTH]
        day_test = perm[DAY]
        #I keep receiving an attribute error on the line below
*       if month_test <= 12 and day_test <= monthdays.get(month_test):
            real_outcomes.add(perm)

    if len(realOutcomes) > 1:
        return "Ambiguous"
    else:
        return "%02d/%02d/%02d" % realOutcomes.pop()

问题是 monthdays 没有 get() 方法,那是因为 monthdaysset,而不是 dict你可能期望。

查看您的代码,列表或元组似乎适合 monthdays。一组没有用,因为它没有排序并且不能包含重复项:

monthdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

然后:

if month_test < len(monthdays) and day_test <= monthdays[month_test]:

您的代码表明您最终会想要处理数年。在这种情况下,您应该查看 calendar module. It provides function monthrange(),它给出了给定年份和月份的天数,并且它处理闰年。

from calendar import monthrange

try: 
    if 1 <= perm[DAY] <= monthrange(perms[YEAR], perm[MONTH])[1]:
        real_outcomes.add(perm)
except ValueError as exc:
    print(exc)    # or pass if don't care

设置对象('monthdays' 在你的例子中)没有属性 'get'

您应该对其进行迭代或将其转换为列表,例如:

list(monthdays)[0] 将 return 结果列表的第一项