python - 如何打印最大长度的字典键?
问题描述
x = {'0': 'test1',
'1': 'test2',
'98hbu98hg7': 'test4',
'21292392392494223423432423': 'test3'}
print(max(x.keys()))
打印出来:
98hbu98hg7
代替:
21292392392494223423432423
难道我做错了什么?
解决方案
默认情况下,通过比较max
返回最大的项目。意思是,使用. 并且由于您的键是字符串,因此会打印出来,因为它在字典上是最大的(因为在 之后)。<
'98hbu98hg7'
9
2
您可以使用key
关键字参数指定不同的排序函数:
x = {'0': 'test1', '1': 'test2', '98hbu98hg7': 'test4', '21292392392494223423432423': 'test3'}
print(max(x.keys(), key=len))
这打印:
21292392392494223423432423
推荐阅读
- java - Java类图中带有接口参数的构造函数
- javascript - 面临断开链接检查器的问题
- json - 需要一个“int”类型的值,但在 Flutter 中得到一个“String”类型的值
- python - 如何为每个子图设置不同的 x 和 y 轴?
- file-copying - 如何将 Google Drive 文件从一个帐户移动到另一个帐户,以保留与其他人共享的访问权限
- javascript - 反应布尔属性不起作用,视频不自动播放
- sql - 触发后如何删除lockTable?
- javascript - 我有一个可统一的数组,它是通过从服务器获取数据创建的
- sql - 使用 IN 条件选择行并分组
- xaml - UWP 全局覆盖默认画笔