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

2024-04-19 23:46:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表数组

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

蒂亚!你知道吗


Tags: 字符串答案hello列表数组hiwherelist
3条回答

在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]))

作为旁注,一般不建议为标准标识符赋值,比如list。你知道吗

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

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}

只需遍历^{}的三元组并打印出最长单词的长度:

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}

这比为每个长度存储变量更好。你知道吗

相关问题 更多 >