首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >交换列表中的单词

交换列表中的单词
EN

Stack Overflow用户
提问于 2022-10-05 04:46:54
回答 2查看 84关注 0票数 -2

我的作业是编写一个Python程序,该程序允许用户输入两个句子,然后以交错的方式将两个句子的单词放到列表中,并打印出来,如下例所示:

代码语言:javascript
代码运行次数:0
运行
复制
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"]

我试过这个,但是用两个不同长度的短语不太好

代码语言:javascript
代码运行次数:0
运行
复制
from itertools import cycle

list1=[]

list2=[]

phrase1=str(input("Enter phrase 1: "))

phrase2=str(input("Enter phrase 2: "))

list1=phrase1.split()

list2=phrase2.split()

print("The phrase 1 is: " + str(phrase1))

print("The phrase 2 is: " + str(phrase2))

res = [ele for comb in zip(lista1, lista2) for ele in comb]

print("Interleaved List : " + str(res))
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-05 06:21:22

您这样做的方式将取决于当两个输入字符串没有相同数量的元素时,结果应该是什么样子。你可能想要这样的东西:

代码语言:javascript
代码运行次数:0
运行
复制
from itertools import zip_longest

s1 = 'Today I went to the sandy beach'
s2 = 'Tomorrow I will travel to Europe'

result = []

for w1, w2 in zip_longest(s1.split(), s2.split()):
    if w1:
        result.append(w1)
    if w2:
        result.append(w2)

print(result)

输出:

代码语言:javascript
代码运行次数:0
运行
复制
['Today', 'Tomorrow', 'I', 'I', 'went', 'will', 'to', 'travel', 'the', 'to', 'sandy', 'Europe', 'beach']
票数 0
EN

Stack Overflow用户

发布于 2022-10-05 05:09:50

对于长度不同的短语,可以使用最长

代码语言:javascript
代码运行次数:0
运行
复制
from itertools import cycle, zip_longest

list1=[]

list2=[]

phrase1=str(input("Enter phrase 1: "))

phrase2=str(input("Enter phrase 2: "))

list1=phrase1.split()

list2=phrase2.split()

print("The phrase 1 is: " + str(phrase1))

print("The phrase 2 is: " + str(phrase2))

res = [ele for comb in zip_longest(list1, list2) for ele in comb]

print("Interleaved List : " + str(res))

这将产生如下结果:

输入短语1:今天我去了海滩

输入短语2:明天我将去欧洲和美国旅行。

第一句是:今天我去海滩了。

第二句是:明天我要去欧洲和美国旅行。

交错列表:“今天”、“明天”、“我”、“我”、“去”、“威尔”、“到”、“旅行”、“到”、“海滩”、“欧洲”、“None”、“None”、“America”

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73956030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档