Python属性错误if statemens

2024-09-29 22:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为这个代码工作了一天。几个小时后,它一直在说我在第26行有一个属性错误。不幸的是,我只有这些信息。我尝试了无数不同的方法来修复它,并搜索了许多网站/论坛。谢谢你的帮助。代码如下:

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()

Tags: 代码testreturnifrealitertoolsdayperm
2条回答

问题是monthdays没有get()方法,这是因为{}是一个set,而不是你可能预期的dict。在

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

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

然后:

^{pr2}$

你的代码表明你最终会想处理好几年。在这种情况下,您应该看看^{}模块。它提供了函数^{},该函数给出给定年份和月份的天数,并处理闰年。在

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

set objects(在您的示例中为monthdays)没有属性“get”

您应该迭代它或将其转换为list,例如:

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

相关问题 更多 >

    热门问题