如何在python中基于连续索引作为整个列表创建列表的所有排列?

时间:2017-03-25 09:24:57

标签: python

这是我的代码(我使用的是python 2.x):

import itertools

def grouper(input_list, n = 2):
    for i in xrange(len(input_list) - (n - 1)):
        yield input_list[i:i+n]

def list_of_lists(num):
    nums = list(map(int,str(num)))
    for first, second, third, fourth in grouper(nums, 4):
        x = first, second, third, fourth
        xx = list(x)
        print xx

这是我的输入:

a = 1232331
list_of_lists(a)

这是我的输出:

[1, 2, 3, 2]
[2, 3, 2, 3]
[3, 2, 3, 3]
[2, 3, 3, 1]

但我希望输出为:

[[1, 2, 3, 2], [2, 3, 2, 3], [3, 2, 3, 3], [2, 3, 3, 1]]

1 个答案:

答案 0 :(得分:0)

您可以使用zip方法获取组合:

try:
    from itertools import izip as zip
except ImportError:
    pass


x = [1, 2, 3, 4, 5, 6]


def getCombin(n, l):
    if len(l) < n:
        return None
    else:
        return list(zip(*(x[i:] for i in range(n))))


print(getCombin(3,x))

输出:

[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

如果您使用的是Python2.x,则可以导入izip

from itertools import izip as zip