我的作业是编写一个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))
发布于 2022-10-05 06:21:22
您这样做的方式将取决于当两个输入字符串没有相同数量的元素时,结果应该是什么样子。你可能想要这样的东西:
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']
发布于 2022-10-05 05:09:50
对于长度不同的短语,可以使用最长
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”
https://stackoverflow.com/questions/73956030
复制相似问题