3 回答

TA贡献1802条经验 获得超6个赞
这是一种如何使用切片进行操作的方法。
def intersperse(one, two):
a = one.split()
b = two.split()
sentence = [None for i in range(len(a) + len(b))]
min_len = min(len(a), len(b))
sentence[:2*min_len:2] = a[:min_len]
sentence[1:2*min_len:2] = b[:min_len]
rest = a[min_len:] if len(a) > min_len else b[min_len:]
sentence[2*min_len:] = rest
return " ".join(sentence)
print(intersperse("a aa aaa", "b"))
print(intersperse("a aa aaa", "b bb"))
print(intersperse("a aa aaa", "b bb bbb"))
print(intersperse("a aa aaa", "b bb bbb bbbb"))
输出:
a b aa aaa
a b aa bb aaa
a b aa bb aaa bbb
a b aa bb aaa bbb bbbb

TA贡献1934条经验 获得超2个赞
你只需要在你用完字的时候处理这个案子。还有句子1 = ''之类的东西
sentence1 = "a bee went buzz"
sentence2 = "a dog went on the bus to Wagga Wagga"
# Single space all whitespace, then split on space
words1 = ' '.join(sentence1.split()).split()
words2 = ' '.join(sentence2.split()).split()
# What is the maximum number of outputs
max_len = max( len(words1), len(words2) )
# Loop through all our words, using pairs, but handling
# differing sizes by skipping
sentence = ''
for i in range(max_len):
if (len(words1) > 0):
w1 = words1.pop(0)
sentence += w1 + ' '
if (len(words2) > 0):
w2 = words2.pop(0)
sentence += w2 + ' '
print(sentence)
添加回答
举报