-1

For example, I define a function like this to process several text files

def file_process(file):  
    procedures
    ...   
    return (a,b,c)

If I have 5 text files, how can I let all of them get through this function, and the output result is assign to each file's outcome.

The objective is like:

x1, y1, z1 = file_process(a.txt)    
x2, y2, z2 = file_process(b.txt)    
x3, y3, z3 = file_process(c.txt)   
x4, y4, z4 = file_process(d.txt)    
x5, y5, z5 = file_process(e.txt) 

but of course this kind of typing is stupid. So if I try for loop:

for f in [a.txt, b.txt, c.txt, d.txt, e.txt]:
     x,y,z = file_process(f)

then how to ensure the result separately assigned to every text file's outcome?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
wflwo
  • 51
  • 1
  • 1
  • 5
  • In this case maybe a list of either: dictionaries with the keys `'x'`, `'y'` and `'z'`; or tuples `(x, y, z)`. – jonrsharpe Mar 12 '18 at 18:06
  • you can use a dictionary or an array to store corresponding tuples (x,y,z). In case of dict, your func can return key-value pair having filename as key and tuple as value. – NightFury Mar 12 '18 at 18:09
  • it depends on how you are going to access them later, if you know x1, y1, z1 comes from the first file and a.txt is the first file, you can use a list of tuples, but the best approach would be to use a dict, where keys are file names, values are a tuple containing return values from the function. An example of this would look like this: `d = {"a.txt": (x1, y1, z1), "b.txt": (x2, y2, z2) ...}`; and assuming file names are in a list, example code would be: `d = {f: file_process(f) for f in filenames_list}` – QnARails Mar 12 '18 at 18:10
  • @QnARails, @ NightFury got the idea! thanks – wflwo Mar 12 '18 at 19:05

1 Answers1

0

You can also do it like this way. Hereby I am assigning the results to a list.

results = []
for f in [a.txt, b.txt, c.txt, d.txt, e.txt]:
    results.append(file_process(f))
Nils
  • 2,665
  • 15
  • 30