为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白板的微信 2021-08-11 22:08:55
现在,如果两个列表的长度相同,代码就可以在列表中交替出现一个句子。但如果列表长度不同,它就不会运行。我希望更长的列表继续打印它们交替完成的列表。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()
查看完整描述

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


查看完整回答
反对 回复 2021-08-11
?
撒科打诨

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)



查看完整回答
反对 回复 2021-08-11
  • 3 回答
  • 0 关注
  • 208 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号