tags:

views:

35

answers:

3

I want to create path of files from list.

pathList = [['~/workspace'], ['test'], ['*'], ['*A', '*2'], ['*Z?', '*1??'], ['*'], ['*'], ['*'], ['*.*']]

and I want

[['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*']]

[['', '~/workspace', 'test', '*', '*A', '*1??', '*', '*', '*', '*.*']]

[['', '~/workspace', 'test', '*', '*2', '*Z?', '*', '*', '*', '*.*']]

[['', '~/workspace', 'test', '*', '*2', '*1??', '*', '*', '*', '*.*']]

I try to create it from for loop but I get

[['', '~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*', '*1??', '*', '*', '*', '*.*', '*2', '*Z?', '*', '*', '*', '*.*', '*1??', '*', '*', '*', '*.*']]

How can I do? Please help me.

Thank you.

+1  A: 

In Python 2.6 or newer you can use itertools.product:

import itertools
for x in itertools.product(*pathList):
    print x
Mark Byers
+1  A: 

I'm not sure I understand the question, but I think you want itertools.product:

print( list( itertools.product( *pathList ) ) )
>>> [('~/workspace', 'test', '*', '*A', '*Z?', '*', '*', '*', '*.*'), 
    ('~/workspace', 'test', '*', '*A', '*1??', '*', '*', '*', '*.*'), 
    ('~/workspace', 'test', '*', '*2', '*Z?', '*', '*', '*', '*.*'), 
    ('~/workspace', 'test', '*', '*2', '*1??', '*', '*', '*', '*.*')]

This yield all possible paths, taking one element from each nested list.

katrielalex
+2  A: 

Anticipating the next step - you can create paths like this

>>> import os, itertools
>>> [os.path.join(*x) for x in  itertools.product(*pathList)]
['~/workspace/test/*/*A/*Z?/*/*/*/*.*',
 '~/workspace/test/*/*A/*1??/*/*/*/*.*',
 '~/workspace/test/*/*2/*Z?/*/*/*/*.*',
 '~/workspace/test/*/*2/*1??/*/*/*/*.*']

and here is a version using itertools.starmap

>>> from itertools import starmap
>>> starmap(os.path.join, itertools.product(*pathList))
<itertools.starmap object at 0xb77d948c>
>>> list(_)
['~/workspace/test/*/*A/*Z?/*/*/*/*.*',
 '~/workspace/test/*/*A/*1??/*/*/*/*.*',
 '~/workspace/test/*/*2/*Z?/*/*/*/*.*',
 '~/workspace/test/*/*2/*1??/*/*/*/*.*']
gnibbler