Create name of path files from list
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.
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??/*/*/*/*.*']
In Python 2.6 or newer you can use itertools.product
:
import itertools
for x in itertools.product(*pathList):
print x
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.
精彩评论