交换列表中的单词



我的作业是编写一个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"]

我试过这个,但不能很好地使用两个不同长度的短语

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))

执行此操作的方式将取决于当两个输入字符串的元素数量不相等时的结果。你可能想要这样的东西:

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)

输出:

['Today', 'Tomorrow', 'I', 'I', 'went', 'will', 'to', 'travel', 'the', 'to', 'sandy', 'Europe', 'beach']

对于不同长度的短语,可以使用itertools.zip_lengest

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:明天我将前往欧洲和美国

短语1是:今天我去了海滩

短语2是:明天我将前往欧洲和美国

交错列表:["今天"、"明天"、"我"、"I"、"去了"、"将要"、"到"、"旅行"、"the"、"to"、"beach"、"Europe"、、"and"、无"America"]

最新更新