python - 如何从每个列表匹配索引的列表数组中获取最长的字符串长度?
问题描述
我有一个列表形式的数组
list = [['hello','hi','hey'],['where','when','why'],['him','herself','themselves']]
我想比较list[0][0]
tolist[1][0]
和的长度list[2][0]
,基本上是所有第一个索引,并获得最长字符串大小的长度。
它必须遍历列表,因为列表中的项目数和列表数可以是任意大小。
例如,这个的答案应该是
length1 = 5
length2 = 6 #('herself' is longer than 'hi' and 'when')
length3 = 10
蒂亚!
解决方案
您不需要创建可变数量的变量。您可以使用列表推导式或字典:
L = [['hello','hi','hey'],['where','when','why'],['him','herself','themselves']]
# list comprehension
res_list = [max(map(len, i)) for i in zip(*L)]
[5, 7, 10]
# dictionary from enumerated generator expression
res_dict = dict(enumerate((max(map(len, i)) for i in zip(*L)), 1))
{1: 5, 2: 7, 3: 10}
推荐阅读
- export - Premiere Pro 导出较旧的 DVCPRO50 视频格式
- excel - 将宏使用日志保存到 SharePoint
- firebase - Firestore,Flutter,Async:方法不等待异步方法完成
- javascript - 反应管理员:
包裹在 div 中时组件元素不呈现 - runtime - datasmith运行时插件导入datasmith文件后如何获取场景属性
- python - 按以前的增量在 Pandas 中自动填充日期时间
- javascript - 单击同一div内的单选按钮时如何更改div的边框颜色?
- node.js - 不定义代理但得到“当 package.json 中指定“代理”时错误
- javascript - 我想使用 MERN 为多个用户提供不同的私人文件
- c++ - 我如何在 file.bin c++ ofstream::write 中写入 x00