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

Python实现两个句子单词的交错合并列表,解决长度不一致问题

解决Python句子单词交错合并时长度不一致的问题

你需要实现的功能是让用户输入两个句子,拆分单词后按交错方式合并成列表,示例如下:

Sentence 1: Today I went to the beach
Sentence 2: Tomorrow I will travel to Europe
输出:["Today", "Tomorrow", "I", "I", "went", "will", "to","travel", "the", "to", "beach", "Europe"]

你的现有代码存在两个问题:

  1. 变量名错误:lista1、lista2应该是list1、list2
  2. 核心逻辑缺陷:zip()只会遍历到两个列表中较短的那个的长度,较长列表里剩余的单词会被直接丢弃,导致结果不完整

下面是两种可行的修正方案:

方案1:手动遍历到最大长度

逻辑直观易懂,适合初学者理解:

phrase1 = input("Enter phrase 1: ")
phrase2 = input("Enter phrase 2: ")

list1 = phrase1.split()
list2 = phrase2.split()

print(f"The phrase 1 is: {phrase1}")
print(f"The phrase 2 is: {phrase2}")

res = []
max_len = max(len(list1), len(list2))

for i in range(max_len):
    if i < len(list1):
        res.append(list1[i])
    if i < len(list2):
        res.append(list2[i])

print(f"Interleaved List : {res}")

方案2:使用itertools.zip_longest

借助标准库工具简化代码,需要过滤掉工具自动填充的None值:

from itertools import zip_longest

phrase1 = input("Enter phrase 1: ")
phrase2 = input("Enter phrase 2: ")

list1 = phrase1.split()
list2 = phrase2.split()

print(f"The phrase 1 is: {phrase1}")
print(f"The phrase 2 is: {phrase2}")

# 列表推导式版本,简洁高效
res = [ele for pair in zip_longest(list1, list2) for ele in pair if ele is not None]

print(f"Interleaved List : {res}")

两种方案都能处理两个句子单词数不同的情况:比如当第一个句子有3个单词、第二个有2个时,结果会是[单词1-1, 单词2-1, 单词1-2, 单词2-2, 单词1-3],完全符合交错合并的需求。

内容的提问来源于stack exchange,提问作者Manuel Deza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:40:25