You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何从逗号分隔字符串中找出所有长度最长的字符串

问题解答

为什么现有代码只返回一个结果

Python内置的max()函数设计逻辑为:当多个元素同时满足最大值条件时,仅返回第一个匹配到的元素,所以你在示例1中只会得到第一个出现的最长字符串abcdefghi,不会返回后续长度相同的barracuda。

实现返回所有最长子串的方法

你可以分三步完成需求:

  • 第一步:用逗号拆分原字符串得到子串列表
  • 第二步:计算所有子串的最大长度
  • 第三步:筛选出所有长度等于最大长度的子串

通用实现代码

def get_all_longest(words_str):
    word_list = words_str.split(',')
    max_len = max(len(word) for word in word_list)
    return [word for word in word_list if len(word) == max_len]

示例1运行测试

words = 'run,barn,abcdefghi,yellow,barracuda,shark,fish,swim'
print(get_all_longest(words))
# 输出结果:['abcdefghi', 'barracuda']

示例2运行测试

words = 'fishes,sam,gollum,sauron,frodo,balrog'
print(get_all_longest(words))
# 输出结果:['fishes', 'gollum', 'sauron', 'balrog']

内容的提问来源于stack exchange,提问作者Kunal Tanwar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:36:03