J R
J R

Reputation: 181

Leaving one item out in a python list and print paths

Given a large number of research subjects ("SUBJ"), I need to create blocks of absolute paths (as strings) that leave one subject out each time.

For example, I need something like:

/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

etc...

Given:

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

The result in my interactive session is something like this:

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']

So far, so good.

My question is, how can I plug these into my file paths, to get the result like the one above? I need to plug each "position" in the array into a stand-alone text string. Thanks in advance,

Upvotes: 0

Views: 2097

Answers (1)

Nicolas78
Nicolas78

Reputation: 5144

what about

directory = "c:\\..."
import os.path
paths = [os.path.join(directory, filename) for filename in filenames]

?

Btw you can save the repetitions of your subject names by a function like

def loo(x):
    return [[el for el in x if el!=x[i]] for i in range(len(x))]

Update ok everything together:

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:\\')

Try running that, results in

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

Upvotes: 3

Related Questions