首页 > 解决方案 > 如何从每个列表匹配索引的列表数组中获取最长的字符串长度?

问题描述

我有一个列表形式的数组

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

蒂亚!

标签: pythonstringlist

解决方案


您不需要创建可变数量的变量。您可以使用列表推导式或字典:

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}

推荐阅读