[英]Length of string in sublist within a list python
I have a list of sublists of anagrams such as 我有一个字谜的子列表,例如
L = [['terrible', 'elbirret'],
['supermonster', 'retsnomrepus'],
['you', 'uoy', 'oyu'],
['pears', 'reaps', 'spear', 'spera']]
How do I write a function that will give me the sublist or anagram group that has the longest anagrams. 如何编写一个函数,该函数将为我提供字谜最长的子列表或字谜组。
ie if the list were 即如果列表是
L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]
it would give me 它会给我
['monster', 'sternom']
Using max
with a key function to get the list with longest strings: 通过键函数使用
max
来获取最长字符串的列表:
>>> L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]
>>> max(L, key=lambda xs: len(xs[0]))
['monster', 'sternom']
UPDATE 更新
What if there were multiple sublists with longest of the same length?
如果存在多个具有相同长度的最长子列表,该怎么办?
Find the maximum length. 找到最大长度。 Filter sublist based on the length:
根据长度过滤子列表:
>>> L = [['largest', 'artlegs'], ['spear', 'pears', 'reaps'], ['monster', 'sternom']]
>>> M = max(len(xs[0]) for xs in L)
>>> [xs for xs in L if len(xs[0]) == M]
[['largest', 'artlegs'], ['monster', 'sternom']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.