当一个列表较长时,备用2个列表python

时间:2018-11-09 01:33:35

标签: 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()

4 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

def intersperse(one, two):
    a = one.split()
    b = two.split()
    sentence = " "

    if len(a) < len(b):
        while a:
            sentence += a.pop(0) + " " + b.pop(0) + " "
        while b:
            sentence += b.pop(0) + " "
    else:
        while b:
            sentence += a.pop(0) + " " + b.pop(0) + " "
        while a:
            sentence += a.pop(0) + " "

    print(sentence)


one = 'This is the long sentence'
two = 'Short sentence'

intersperse(one, two)

输出

This Short is sentence the long sentence 

请注意,上面的代码 只是您可以在intersperse中进行操作的一个示例。 pythonic 的另一种选择是使用zip_longest

from itertools import zip_longest


def intersperse(one, two):
    a = one.split()
    b = two.split()
    sentence = ' '.join([e for pair in zip_longest(a, b) for e in pair if e])
    print(sentence)


one = 'This is the long sentence'
two = 'Short sentence'

intersperse(one, two)

输出

This Short is sentence the long sentence

答案 1 :(得分:0)

当您用完所有文字时,您只需要处理该案件即可。 也像句子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)

答案 2 :(得分:0)

from itertools import zip_longest
for one_el, two_el in zip_longest(a, b):
   one_el = one_el or " "
   two_el = two_el or " "
   sentence += one_el + " " + two_el + " "

答案 3 :(得分:0)

这里是切片的一种方法。

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