Python 如何从每个列表匹配索引的列表数组中获取最长的字符串长度?

Python 如何从每个列表匹配索引的列表数组中获取最长的字符串长度?,python,string,list,Python,String,List,我在表单中有一个列表数组 list = [['hello','hi','hey'],['where','when','why'],['him','herself','themselves']] 我想比较list[0][0]到list[1][0]和list[2][0]的长度,基本上是所有的第一个索引,并获得最长字符串大小的长度 它必须遍历列表,因为列表中的项目数和列表数可以是任意大小 例如,答案应该是 length1 = 5 length2 = 6 #('herself' is longer t

我在表单中有一个列表数组

list = [['hello','hi','hey'],['where','when','why'],['him','herself','themselves']]
我想比较
list[0][0]
list[1][0]
list[2][0]
的长度,基本上是所有的第一个索引,并获得最长字符串大小的长度

它必须遍历列表,因为列表中的项目数和列表数可以是任意大小

例如,答案应该是

length1 = 5
length2 = 6 #('herself' is longer than 'hi' and 'when')
length3 = 10

蒂亚

只需查看中的三个字母,然后打印出最长单词的长度:

lst = [['hello','hi','hey'],['where','when','why'],['him','herself','themselves']]

for i, triple in enumerate(zip(*lst), start=1):
    print('length%d = %d' % (i, len(max(triple, key=len))))

# length1 = 5
# length2 = 7
# length3 = 10
或作为字典:

{'length%d' % i: len(max(e, key=len)) for i, e in enumerate(zip(*lst), start=1)}
# {'length1': 5, 'length2': 7, '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}

这比为每个长度存储变量要好

在Python中有很多方法

array = [['hello','hi','hey'],
         ['where','when','why'],
         ['him','herself','themselves']]

length1 = 0
for elem in array:
    if length1 < len(elem[0]):
        length1 = len(elem[0])

length2 = max(array, key=lambda elem: len(elem[1]))

from itertools import accumulate
length3 = accumulate(array,
        lambda e1, e2: max(len(e1[2]), len(e2[2]))
array=[['hello'、'hi'、'hey'],
['where'、'when'、'why'],
[“他”、“她自己”、“他们自己]]
长度1=0
对于阵列中的元素:
如果长度1

作为旁注,通常不建议为标准标识符分配某些内容,例如
list

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

{'length%d' % i: len(max(e, key=len)) for i, e in enumerate(zip(*lst), start=1)}
# {'length1': 5, 'length2': 7, '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}

请包含未产生所需输出的代码。请显示您迄今为止尝试的代码和获得的结果。我认为您需要
length2=7
,因为
'self'
有7个字符。