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

寻求列表元素拆分并保留原元素的更高效实现方案

优化列表元素拆分并保留原元素的实现方案

你的需求是:遍历字符串列表,单个单词的元素保留拆分后的单元素列表;多单词的元素则生成「拆分后的单词列表 + 原字符串」的组合列表,最终汇总所有结果。

原实现的可优化点

原代码逻辑正确,但存在两个可改进的地方:

  1. 直接修改拆分后的临时列表(splitted_l.append(l)),如果后续需要复用该临时列表的原始拆分结果会产生副作用;
  2. 写法可以更简洁,利用Python语法特性提升代码可读性和执行效率。

优化方案

方案1:列表推导式(简洁直观)

如果不需要考虑重复拆分的性能损耗,可用一行列表推导式实现,代码更紧凑:

lists = ["the", "I am there", "call me"]
final_list = [s.split() if len(s.split()) == 1 else s.split() + [s] for s in lists]
print(final_list)

方案2:避免重复拆分(高效推荐)

对于大量长字符串的场景,重复调用split()会浪费计算资源,可先计算一次拆分结果再判断。Python 3.8+支持的赋值表达式能让写法更简洁:

lists = ["the", "I am there", "call me"]
final_list = [splitted if len(splitted) == 1 else splitted + [s] for s in lists if (splitted := s.split())]

如果需要兼容Python 3.8以下版本,用常规循环写法也能达到同样的高效性:

lists = ["the", "I am there", "call me"]
final_list = []
for s in lists:
    splitted = s.split()
    final_list.append(splitted if len(splitted) == 1 else splitted + [s])

输出结果

以上优化方案的输出均与原代码一致:

[['the'], ['I', 'am', 'there', 'I am there'], ['call', 'me', 'call me']]

内容的提问来源于stack exchange,提问作者research comp5800

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:02:22