在不等列表上使用zip_longest,但重复最后一个条目而不是不返回None [英] Using zip_longest on unequal lists but repeat the last entry instead of returning None

查看:20
本文介绍了在不等列表上使用zip_longest,但重复最后一个条目而不是不返回None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个关于此的现有主题 将python中的不相等列表压缩到一个列表中,该列表不会从要压缩的较长列表中删除任何元素

There is an existing thread about this Zipping unequal lists in python in to a list which does not drop any element from longer list being zipped

但这不是我所追求的. 除了返回None之外,我还需要它来复制列表中的上一个条目.

But it's not quite I'm after. Instead of returning None, I need it to copy the previous entry on the list.

这可能吗?

a = ["bottle","water","sky"]
b = ["red", "blue"]
for i in itertools.izip_longest(a,b):
    print i

#result
# ('bottle', 'red')
# ('water', 'blue')
# ('sky', None) 

# What I want on the third line is
# ('sky', 'blue')

推荐答案

itertools.izip_longest采用可选的fillvalue参数,该参数提供在精简列表用尽后使用的值. fillvalue默认为None,给出您在问题中显示的行为,但是您可以指定其他值以获取所需的行为:

itertools.izip_longest takes an optional fillvalue argument that provides the value that is used after the shorter list has been exhausted. fillvalue defaults to None, giving the behaviour you show in your question, but you can specify a different value to get the behaviour you want:

    fill = a[-1] if (len(a) < len(b)) else b[-1]
    for i in itertools.izip_longest(a, b, fillvalue=fill):
        print i

(显然,如果相同的列表总是较短的列表,那么选择填充字符会更加容易.)

(Obviously if the same list is always the shorter one then choosing the fill character is even easier.)

这篇关于在不等列表上使用zip_longest,但重复最后一个条目而不是不返回None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆