Python:如何获取最长元素之前的列表中的所有元素? [英] Python:How can i get all the elements in a list before the longest element?

查看:701
本文介绍了Python:如何获取最长元素之前的列表中的所有元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,例如

l = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']

如何在出现最长元素之前而不是之后的元素中获取列表中的所有元素?

How can I get all the elements in the list before the occurrance of the longest element and not the ones that come after?

推荐答案

这有效:

lst = ['abc34','def987','ghij','klmno','pqrstuvwxyz1234567','98765','43','210abc']
idx, maxLenStr = max(enumerate(lst), key=lambda x:len(x[1]))
sublist = lst[:idx]

它只循环遍历列表一次以确定最大长度,而使用max()然后index()遍历所有元素两次两次.它还将最大长度的字符串存储在maxLenStr中,并将其存储在idx中的索引,以防万一.

It only iterates through the list once for determining the maximum length, whereas using max() and then index() iterates twice over all the elements. It also stores the string with the maximum length in maxLenStr and the index where it was found in idx, just in case.

这篇关于Python:如何获取最长元素之前的列表中的所有元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆