在python中创建子列表中的子列表

时间:2014-10-09 20:00:04

标签: python list

我想在子列表中创建一系列子列表:

original = range(1,13)

我读了另一篇文章,提供了在列表中创建子列表的解决方案:

>>> [original[i:i+2] for i in range(0,len(original),2)]
>>> [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12]]

但我怎样才能达到这个结果呢?

[ [[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]] ] 

3 个答案:

答案 0 :(得分:4)

您可以将子列表操作定义为函数并将其应用两次。这可能是低效的,因为它将在构建具有最佳子列表级别的列表之前构建中间列表。但是,更容易阅读,因为您已经熟悉了第一步,因为您在提出这个问题时使用了它。

def nest_in_pairs(original):
    return [original[i:i+2] for i in range(0,len(original),2)]

print nest_in_pairs(nest_in_pairs(original))

更有效的方法是创建一个生成器,从列表的前面生成最多两个项目的列表。然后链接他们。

from types import GeneratorType

def yield_next_two(seq):
    if not isinstance(seq, GeneratorType):
        for i in range(0, len(seq), 2):
            yield seq[i:i+2]
    else:
        while True:
            item1 = next(seq)
            try:
                item2 = next(seq)
                yield [item1, item2]
            except StopIteration:
                yield [item1]

pair_generator = yield_next_two(original)

quad_generator = yield_next_two(yield_next_two(original))

next(pair_generator)

next(quad_generator)

您可以在listpair_generator上致电quad_generator以获取整套内容。

以下是将上述代码粘贴到IPython会话后播放的示例:

In [40]: quad_generator = yield_next_two(yield_next_two(original))

In [41]: list(quad_generator)
Out[41]: [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]

In [42]: nearly_eights_generator = yield_next_two(yield_next_two(yield_next_two(original)))

In [43]: list(nearly_eights_generator)
Out[43]: [[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[[9, 10], [11, 12]]]]

答案 1 :(得分:2)

orig = range(1,13)
def squeeze( original ): 
    return [original[i:i+2] for i in range(0,len(original),2)]
print ( squeeze(squeeze(orig)) )

答案 2 :(得分:-1)

您可以运行两次相同的代码:

>>> original = range(1,13)
>>> [original[i:i+2] for i in range(0,len(original),2)]
output --> [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12]]

>>> original = range(1,13)
>>> original = [original[i:i+2] for i in range(0,len(original),2)]
>>> [original[i:i+2] for i in range(0,len(original),2)]
output --> [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]