是否有类似拉链的功能可以垫到最长的长度? [英] Is there a zip-like function that pads to longest length?

查看:26
本文介绍了是否有类似拉链的功能可以垫到最长的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有像 zip() 这样的内置函数 但这会填充结果,因此结果列表的长度是最长输入的长度,而不是最短输入的长度?

<预><代码>>>>a = ['a1']>>>b = ['b1', 'b2', 'b3']>>>c = ['c1', 'c2']>>>邮编(a,b,c)[('a1', 'b1', 'c1')]>>>什么命令在这里?[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

解决方案

在 Python 3 中你可以使用 itertools.zip_longest

<预><代码>>>>列表(itertools.zip_longest(a,b,c))[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

您可以使用 fillvalue 参数填充与 None 不同的值:

<预><代码>>>>列表(itertools.zip_longest(a,b,c,fillvalue='foo'))[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]

使用 Python 2,您可以使用 itertools.izip_longest (Python 2.6+),或者你可以使用 mapNone.这是一个鲜为人知的map 的功能(但 map 在 Python 3.x 中发生了变化,所以这只适用于 Python 2.x).

<预><代码>>>>地图(无,a,b,c)[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

Is there a built-in function that works like zip() but that will pad the results so that the length of the resultant list is the length of the longest input rather than the shortest input?

>>> a = ['a1']
>>> b = ['b1', 'b2', 'b3']
>>> c = ['c1', 'c2']

>>> zip(a, b, c)
[('a1', 'b1', 'c1')]

>>> What command goes here?
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

解决方案

In Python 3 you can use itertools.zip_longest

>>> list(itertools.zip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

You can pad with a different value than None by using the fillvalue parameter:

>>> list(itertools.zip_longest(a, b, c, fillvalue='foo'))
[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]

With Python 2 you can either use itertools.izip_longest (Python 2.6+), or you can use map with None. It is a little known feature of map (but map changed in Python 3.x, so this only works in Python 2.x).

>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]

这篇关于是否有类似拉链的功能可以垫到最长的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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