List Combinations

Shane Geiger sgeiger at ncee.net
Wed Mar 12 10:33:05 EDT 2008


Michael Wieher wrote:
>
>
> 2008/3/12, Gerdus van Zyl <gerdusvanzyl at gmail.com
> <mailto:gerdusvanzyl at gmail.com>>:
>
>     I have a list that looks like this:
>     [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]
>
>     how can I get all the combinations thereof that looks like as follows:
>     3,9,5,4,2
>     3,1,5,4,2
>     3,9,5,4,5
>     3,1,5,4,5
>     etc.
>
>     Thank You,
>     Gerdus
>
>     --
>
>
> list =  [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]
> newList = []
> for l in list:
>    newList.extend(l)
>
> #newList = [3,9,1,5,4,2,5,8]
> list=[]
> for l in newList:
>     if l not in list:
>          list.append(l)
>
> #now list is [3,9,1,5,4,2,8]
>
> list.sort()
>
> #now your list is in sorted order
>
> Then, you can just write a series of for loops to spin off your data
> however you like. 
>
>


def gen(lists):
    out =  '[' + ','.join(["v%s" % i for i in range(len(lists))]) + ']'
    comp = ''.join([ " for v%d in lists[%d]" % (i, i) for i in
range(len(lists))])
    return eval('[ ' + out + comp + ' ]')

a,b,c = [1,2,3],[4,5,6],[7,8,9]

print gen([a, b, c])





-- 
Shane Geiger
IT Director
National Council on Economic Education
sgeiger at ncee.net  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy




More information about the Python-list mailing list