Understanding Python list to return list edge values

If I have a list in python, for example:

stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]

with length n (in this case 9), and I'm interested in creating lists of length n / 2 (in this case 4). I want all possible sets of n / 2 values ​​in the source list, for example:

[1, 2, 3, 4], [2, 3, 4, 5], ..., [9, 1, 2, 3]  

Is there any list comprehension code that I could use to repeat the list and get all of these subscriptions? I'm not interested in the order of values ​​inside lists, I'm just trying to find a smart method for generating lists.

+5
source share
3 answers
>>> stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> n=len(stuff)
>>>
>>> [(stuff+stuff[:n/2-1])[i:i+n/2] for i in range(n)]
[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 1], [8, 9, 1, 2], [9, 1, 2, 3]]
>>>

Note : the above code is based on the assumption from your example

[1, 2, 3, 4], [2, 3, 4, 5], ..., [9, 1, 2, 3]  

, itertools.permutations , .

+5

, itertools (EDIT: , )

, Python 2.5. :

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

stuff = range(9)
what_i_want = [i for i in combinations(stuff, len(stuff)/2)]
+5

itertools.permutations() itertools.combinations() ( , , , [1,2,3,4], [4,3,2,1] ) .

stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]

itertools.permutations(stuff, 4) # will return all possible lists of length 4
itertools.combinations(stuff, 4) # will return all possible choices of 4 elements

, .

Update

, , , , itertools.combinations().

+3

All Articles