gpt4 book ai didi

python - 列表python中子列表中字符串的长度

转载 作者:太空宇宙 更新时间:2023-11-04 10:29:55 25 4
gpt4 key购买 nike

我有一个变位词的子列表列表,例如

L = [['terrible', 'elbirret'],
['supermonster', 'retsnomrepus'],
['you', 'uoy', 'oyu'],
['pears', 'reaps', 'spear', 'spera']]

我如何编写一个函数来为我提供具有最长变位词的子列表或变位词组。

即如果列表是

L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]

它会给我

['monster', 'sternom']

最佳答案

使用 max具有获取最长字符串列表的关键函数:

>>> L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]
>>> max(L, key=lambda xs: len(xs[0]))
['monster', 'sternom']

更新

What if there were multiple sublists with longest of the same 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']]

关于python - 列表python中子列表中字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27415052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com