猿问

当一个列表较长时,替代 2 个列表 python

现在,如果两个列表的长度相同,代码就可以在列表中交替出现一个句子。但如果列表长度不同,它就不会运行。我希望更长的列表继续打印它们交替完成的列表。


def intersperse():

    one = str(input("enter a sentence"))

    two = str(input("enter a sentence"))


    a = one.split()

    b = two.split()

    sentence = " "


    #min_len = min(len(a),len(b))

    if len(a) > len(b):


        min_len = a

    else:

        min_len = b


    for i in min_len:

        sentence += a.pop(0) + " " + b.pop(0) + " "


    print(sentence)




intersperse()


白板的微信
浏览 209回答 3
3回答

呼啦一阵风

这是一种如何使用切片进行操作的方法。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 aaaa b aa bb aaaa b aa bb aaa bbba b aa bb aaa bbb bbbb

撒科打诨

你只需要在你用完字的时候处理这个案子。还有句子1 = ''之类的东西sentence1 = "a bee went buzz"sentence2 = "a dog went on the bus to Wagga Wagga"# Single space all whitespace, then split on spacewords1 = ' '.join(sentence1.split()).split()words2 = ' '.join(sentence2.split()).split()# What is the maximum number of outputsmax_len = max( len(words1), len(words2) )# Loop through all our words, using pairs, but handling # differing sizes by skippingsentence = ''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)
随时随地看视频慕课网APP

相关分类

Python
我要回答