代码之家  ›  专栏  ›  技术社区  ›  Konrad

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

  •  0
  • Konrad  · 技术社区  · 8 年前

    给定词典:

    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
    

    这不是期望的答案 口述月份 包含 Feb

    1 回复  |  直到 8 年前
        1
  •  3
  •   Rakesh    8 年前

    使用 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()) 只是为了删除空元素。