Home > front end >  Pass 2 arguments from a single file into function parameters
Pass 2 arguments from a single file into function parameters

Time:10-13

I have a function:

def process(fa : {str:{str:str}}, state : str, inputs : [str]) -> [None]:

and the parameters' (state : str, inputs : [str]) arguments would come from the file (input_file.txt) with the contents:

even;1;0;1;1;0;1
even;1;0;1;1;0;x
odd;1;0;1;1;0;1

With state being the first element (even/odd) and inputs being a list of the rest of the elements (1,0,x)

Is it possible to pass the contents from the file into the function as arguments?

I've tried comprehension but the return value is nothing near what I am trying to get, and I don't know what else to try after playing around with it for a bit:

proccess( fa, (item[0] for line in input_file for item in line.split(';')), (item[1:] for line in input_file for item in line.split(';') )

CodePudding user response:

Something like this should do it:

for line in open('input_file.txt','rt'):
    state,*inputs = line.strip().split(';')
    process(fa,state,inputs)

CodePudding user response:

for line in input_file for item in line.split(';')

This returns an iterator for each element in each line, hence:

even
1
0
1
1
0
1
even
1
...

Your item[0] and item[1:] does not result in errors because each string ("even", "1", etc) can be indexed.

You probably can try something similar to:

proccess( fa, 
   (line.split(';')[0] for line in input_file),
   (line.split(';')[1:] for line in input_file)
)

By the way you should note that: 1) you are duplicating split() calls, and 2) if input_file is a file then lines only come through once, and 3) you are passing in generators not str/list of strings that the func expects.

  • Related