在Python列表中遗漏一个项目并打印路径
我有很多研究对象(简称“SUBJ”),我需要创建一些绝对路径的块(以字符串形式),每次都漏掉一个对象。
比如,我需要这样的格式:
/path/to/data/SUBJ02
/path/to/data/SUBJ03
/path/to/data/SUBJ04
/path/to/data/SUBJ05
/path/to/data/SUBJ01
/path/to/data/SUBJ03
/path/to/data/SUBJ04
/path/to/data/SUBJ05
等等...
给定:
x = ["SUBJ01","SUBJ02","SUBJ03","SUBJ04","SUBJ05"]
loso = ["SUBJ01","SUBJ02","SUBJ03","SUBJ04","SUBJ05"]
def returnLoso(x,loso):
x1 = [(z) for (z) in x if z !=loso]
print x1
在我的交互式会话中,结果大概是这样的:
In [1]: for i, v in enumerate(loso):
.....: returnLoso(x,v)
.....:
['SUBJ02', 'SUBJ03', 'SUBJ04', 'SUBJ05']
['SUBJ01', 'SUBJ03', 'SUBJ04', 'SUBJ05']
['SUBJ01', 'SUBJ02', 'SUBJ04', 'SUBJ05']
['SUBJ01', 'SUBJ02', 'SUBJ03', 'SUBJ05']
['SUBJ01', 'SUBJ02', 'SUBJ03', 'SUBJ04']
到目前为止,一切都很好。
我的问题是,如何将这些放入我的文件路径中,以得到像上面那样的结果?我需要把数组中的每个“位置”放入一个独立的文本字符串中。提前谢谢!
1 个回答
3
那这个呢
directory = "c:\\..."
import os.path
paths = [os.path.join(directory, filename) for filename in filenames]
?
顺便说一下,你可以通过一个函数来减少你主题名称的重复,比如
def loo(x):
return [[el for el in x if el!=x[i]] for i in range(len(x))]
更新一下,所有内容合在一起:
import os.path
def loo(x):
return [[el for el in x if el!=x[i]] for i in range(len(x))]
def p(subjects, directory):
l = loo(subjects)
for group in l:
for subj in group:
print os.path.join(directory, subj)
print
p(['S1','S2','S3','S4','S5'], 'c:\\')
试着运行一下,结果是
c:\S2
c:\S3
c:\S4
c:\S5
c:\S1
c:\S3
c:\S4
c:\S5
c:\S1
c:\S2
c:\S4
c:\S5
c:\S1
c:\S2
c:\S3
c:\S5
c:\S1
c:\S2
c:\S3
c:\S4