【问题标题】:Getting the top length of a key in Python [duplicate]在Python中获取键的顶部长度[重复]
【发布时间】:2012-08-10 14:43:53
【问题描述】:

可能重复:
Find longest (string) key in dictionary

不折叠。示例:

from functools import reduce
dict = {'t1': 'test1', 'test2': 't2'}
print(len(reduce(lambda x, y: x if len(x) >= len(y) else y, dict.keys())))

有什么方法可以获取字典中最长键的长度(最好是一行)?折叠没有什么问题,但我只是对 Python 3 中是否有另一种方法感兴趣。

【问题讨论】:

    标签: python python-3.x dictionary string-length


    【解决方案1】:

    你可以这样做

    max(map(len, my_dict))
    

    这将获取所有键的长度并提取这些长度的最大值。

    要获得最长的密钥本身,请使用

    max(my_dict, key=len)
    

    【讨论】:

    • 有没有办法只获取长度为 3 个字母的键?
    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 2019-08-17
    • 2011-07-28
    相关资源
    最近更新 更多