Skip to main content
 首页 » 编程设计

python之如何在这里找到最长的字符串

2025年05月04日21softidea

我正在尝试使用以下代码在嵌套列表中查找最长的字符串

table_data = [['apples', 'oranges', 'cherries', 'banana'], 
             ['Alice', 'Bob', 'Carol', 'David'], 
             ['dogs', 'cats', 'moose', 'goose']] 
 
cnt = [""]*3 
for tab in range(len(table_data)): 
    for liel in table_data[tab]: 
        if len(liel) > len(cnt[tab]): 
            cnt[tab]=liel 
print(cnt) 
# ['cherries', 'Alice', 'moose'] 

上面的代码是返回每个列表中最长的字符串,但我认为它的代码很长,还有其他方法可以做到这一点吗?

期望使用列表理解或函数来执行此操作

问候

请您参考如下方法:

Expecting any ways to do this using List comprehension

是的,列表理解是一个不错的选择。

>>> [max(row, key=len) for row in table_data] 
['cherries', 'Alice', 'moose']