views:

103

answers:

3

If I have a list in python such as:

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

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

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

is there some list comprehension code I could use to iterate through the list and retrieve all of those sublists? I don't care about the order of the values within the lists, I am just trying to find a clever method of generating the lists.

+5  A: 

What you need is combinations function from itertools (EDIT: use permutation if the order is important)

Note that this function is not available at Python 2.5. In that case you can copy the code from the above link:

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)

and then

stuff = range(9)
what_i_want = [i for i in combinations(stuff, len(stuff)/2)]
bgbg
The list of numbers was only an example. Would this code work for, say, a list of strings?
mvid
this works on any iterable: string, list of string, sets ...
bgbg
+2  A: 

Use itertools.permutations() or itertools.combinations() (depending on whether you want, for example, both [1,2,3,4] and [4,3,2,1] or not) with the optional second argument to specify length.

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

This is assuming that you don't only want contiguous elements.

Update

Since you specified that you don't care about order, what you're probably looking for is itertools.combinations().

Amber
+4  A: 
>>> 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: above code is based on assumption from your example

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

If you really need all possible values, you need to use itertools.permutations or combinations function as others suggested.

S.Mark