简体   繁体   English

Python TypeError:不可散列的类型:“工作日”

[英]Python TypeError: unhashable type: 'weekday'

I'm trying to generate a human-friendly string representation for a list of dateutil.rrule.weekday objects. 我正在尝试为dateutil.rrule.weekday对象的列表生成人类友好的字符串表示形式。 To this end, I'm trying to create a dictionary WEEKDAY_TO_NAME which maps the object to its string representation: 为此,我试图创建一个字典WEEKDAY_TO_NAME ,将对象映射到其字符串表示形式:

import dateutil.parser
from dateutil.rrule import weekdays as WEEKDAYS
WEEKDAY_NAMES = [name[1] for name in dateutil.parser.parserinfo.WEEKDAYS]

WEEKDAY_TO_NAME = dict(zip(WEEKDAYS, WEEKDAY_NAMES))

However, this leads to a 但是,这导致

TypeError: unhashable type: 'weekday'

Is there any way to get around this (without writing seven if / elif statements)? 有什么办法可以解决这个问题(无需编写七个if / elif语句)?

In Python 3, you need to convert the items in WEEKDAYS to strings: 在Python 3中,您需要将WEEKDAYS的项目转换为字符串:

>>> dict(zip(map(str,WEEKDAYS), WEEKDAY_NAMES))
{'SA': 'Saturday', 'TH': 'Thursday', 'SU': 'Sunday', 'WE': 'Wednesday', 'TU': 'Tuesday', 'MO': 'Monday', 'FR': 'Friday'}

Note the type() of item in WEEKDAYS before conversion is 'dateutil.rrule.weekday' : 需要注意的type()项的WEEKDAYS之前转换为'dateutil.rrule.weekday'

>>> [type(item) for item in WEEKDAYS]
[<class 'dateutil.rrule.weekday'>, <class 'dateutil.rrule.weekday'>, <class 'dateutil.rrule.weekday'>, <class 'dateutil.rrule.weekday'>, <class 'dateutil.rrule.weekday'>, <class 'dateutil.rrule.weekday'>, <class 'dateutil.rrule.weekday'>]

(Thanks to hascode55 and MSeifert for pointing out that the tuple() calls I had before were unnecessary.) (感谢hascode55和MSeifert指出我之前调用过的tuple()不必要。)

I should have perhaps been more clear about what I wanted to achieve: a function weekday_to_string which takes an instance of dateutil.rrule.weekday as input and returns a string such as "Monday". 我应该对要实现的目标更加清楚:一个功能weekday_to_string ,该函数将dateutil.rrule.weekday一个实例作为输入并返回诸如“ Monday”的字符串。 I wanted to use the dictionary as a lookup table inside this function, so it actually would not do to convert the dateutil.rrule.weekday instances to strings first since then I would not be able to look up the input anymore. 我想将字典用作此函数中的查找表,因此实际上不会dateutil.rrule.weekday实例转换为字符串,因为那样以后我将无法再查找输入。

Here is how I implemented it in the end: 这是我最终实现的方式:

def weekday_to_string(weekday):
    '''Converts a dateutil.rrule weekday constant to its full string representation.'''
    WEEKDAY_NAMES = [name[1] for name in dateutil.parser.parserinfo.WEEKDAYS]
    return WEEKDAY_NAMES[WEEKDAYS.index(weekday)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM