2016-07-20 69 views
0

您能否提出一種更好的方式來組合列表中的字符串?通過列表理解結合字符串的習慣方式

下面是一個例子:

[ 'prefix-' + a + '-' + b for a in [ '1', '2' ] for b in [ 'a', 'b' ] ] 

這導致:

['prefix-1-a', 'prefix-1-b', 'prefix-2-a', 'prefix-2-b'] 

實際上下文正在與文件和路徑:

dirs = [ 'dir1', 'dir2' ] 
files = [ 'file1', 'file2' ] 
[ 'home/' + d + '/' + f for d in dirs for f in files ] 

導致:

['home/dir1/file1', 'home/dir1/file2', 'home/dir2/file1', 'home/dir2/file2'] 
+2

這可能是一個問題,更適合於[代碼審查(http://codereview.stackexchange.com/) – Aaron

回答

3

對於文件路徑具體工作,用os.path.join

dirs = ['dir1', 'dir2'] 
files = ['file1', 'file2'] 
[os.path.join('home', d, f) for d in dirs for f in files] 
+1

這似乎是最pythonic方式去解決它(出於下面的答案)。 –

+0

@frist這是我的錯誤。我在原文中糾正了它。 – Luis

1

怎麼樣與str.join

['-'.join(('prefix', a, b)) for a, b in zip('12', 'ab')] 

正如其他人所提到的,你應該使用os.path.join的文件路徑。

0

第一招:['prefix-%s-%s' % (a,b) for a in [1, 2] for b in 'ab']

第二個可能是相同的方式,但您可能需要使用os.path.join標準化的Windows:

[os.path.join('home', dir_, file_) for dir_ in ['dir1', 'dir2'] for file_ in ['file1', 'file2']] 
3

您可以使用列表理解,os.path.join功能和itertools模塊:

[os.path.join('home', a, b) for a, b in itertools.product(ddirs, files)] 
1

您可以使用笛卡爾產品列表。

import itertools 
for element in itertools.product(["1", "2"], ["a", "b"]): 
    print element 

# Gives 
('1', 'a') 
('1', 'b') 
('2', 'a') 
('2', 'b') 

然後加入他們,但是你想要的。