强制字典到元组与字符串上的endwith一起使用

2024-10-02 02:36:54 发布

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

给定词典:

dictMnths = dict((v,k) for k,v in enumerate(calendar.month_abbr))

我希望使用dictMonths类似于下面的元组('Jan','Feb')

'aaFeb'.endswith(('Jan','Feb'))
# True

尝试

keys()

'aaFeb'.endswith(dictMnths.keys())
# TypeError: endswith first arg must be str or a tuple of str, not dict_keys

str()

'aaFeb'.endswith(str(dictMnths.keys()))
# False

这不是期望的答案,因为dictMonths包含Feb


Tags: inforkeyscalendardictjanfeb词典
1条回答
网友
1楼 · 发布于 2024-10-02 02:36:54

使用tuple()应该会有所帮助

import calendar
dictMnths = dict((v,k) for k,v in enumerate(calendar.month_abbr))
print('aaFeb'.endswith(tuple( dictMnths.keys()))) # or 'aaFeb'.endswith(tuple(filter(None, dictMnths.keys())))

输出:

True

注意:我使用filter(None, dictMnths.keys())只是删除空元素

相关问题 更多 >

    热门问题