Python列表转置和填充

时间:2012-05-16 00:05:16

标签: python list fill transpose

我有一个列表列表,每个内部列表的长度为1或n(假设n> 1)。

>>> uneven = [[1], [47, 17, 2, 3], [3], [12, 5, 75, 33]]

我想转置列表,但不是截断较长的列表(与zip一样)或用None填充较短的列表,我想用自己的奇异值填充较短的列表。换句话说,我想得到:

>>> [(1, 47, 3, 12), (1, 17, 3, 5), (1, 2, 3, 75), (1, 3, 3, 33)]

我可以通过几次迭代来完成这项工作:

>>> maxlist = len(max(*uneven, key=len))
>>> maxlist
4
>>> from itertools import repeat
>>> uneven2 = [x if len(x) == maxlist else repeat(x[0], maxlist) for x in uneven]
>>> uneven2
[[1, 1, 1, 1], [47, 17, 2, 3], [3, 3, 3, 3], [12, 5, 75, 33]]
>>> zip(*uneven2)
[(1, 47, 3, 12), (1, 17, 3, 5), (1, 2, 3, 75), (1, 3, 3, 33)]

但是有更好的方法吗?我是否真的需要提前知道maxlist才能完成此任务?

3 个答案:

答案 0 :(得分:7)

您可以永远重复一个元素列表:

uneven = [[1], [47, 17, 2, 3], [3], [12, 5, 75, 33]]

from itertools import repeat

print zip(*(repeat(*x) if len(x)==1 else x for x in uneven))

答案 1 :(得分:4)

您可以改为使用itertools.cycle()

>>> from itertools import cycle
>>> uneven3 = [x if len(x) != 1 else cycle(x) for x in uneven]
>>> zip(*uneven3)
[(1, 47, 3, 12), (1, 17, 3, 5), (1, 2, 3, 75), (1, 3, 3, 33)]

这意味着您不需要提前知道maxlist

答案 2 :(得分:0)

我真的很喜欢@ chris-morgan关于模拟itertools.izip_longest的想法,所以当我最终获得灵感时,我写了一个izip_cycle函数。

def izip_cycle(*iterables, **kwargs):
    """Make an iterator that aggregates elements from each of the iterables.
    If the iterables are of uneven length, missing values are filled-in by cycling the shorter iterables.
    If an iterable is empty, missing values are fillvalue or None if not specified.
    Iteration continues until the longest iterable is exhausted.
    """
    fillvalue = kwargs.get('fillvalue')
    counter = [len(iterables)]
    def cyclemost(iterable):
        """Cycle the given iterable like itertools.cycle, unless the counter has run out."""
        itb = iter(iterable)
        saved = []
        try:
            while True:
                element = itb.next()
                yield element
                saved.append(element)
        except StopIteration:
            counter[0] -= 1
            if counter[0] > 0:
                saved = saved or [fillvalue]
                while saved:
                    for element in saved:
                        yield element
    iterators = [cyclemost(iterable) for iterable in iterables]
    while iterators:
        yield tuple([next(iterator) for iterator in iterators])

print list(izip_cycle([], range(3), range(6), fillvalue='@'))