Python Forum
Looking for a sleeker way to code this function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looking for a sleeker way to code this function
#1
Hello friends,

I am wondering if anyone could suggest a more simple way of coding this function? I am building a formatted string for a report based on an input matrix. The input matrix contains one or more lists of strings. Each list in this matrix could contain 1 to 16 (maybe more) string variables.

So based on the length of each list in my matrix, I am building a formatted string based on the number of strings in my list. The code I have here works just fine, but it feels like something which could be done more efficiently.

for input_list in input_matrix:
     list_length = len(input_list)
          if list_length == 1:
               formatted_str = format_str.format(input_list[0])
          elif list_length == 2:
               formatted_str = format_str.format(input_list[0],input_list[1])
          elif list_length == 3:
               formatted_str = format_str.format(input_list[0],input_list[1],input_list[2])
          elif list_length == 4:
               formatted_str = format_str.format(input_list[0],input_list[1],input_list[2],input_list[3])
               ......
Sincere thanks for your suggestions!
C.J.
Reply
#2
This really depends on how your format works. But a couple of options might be:

Assign all the variables. Place something like the empty string as placeholders in the input list. Then they're present for the format. Might not work if you're putting in separators.

Concatenate/join the result of the format. Loop over the contents of input_list, formatting each component. Then join() or concatenate all the formatted strings together.

In some cases (like a table), it might be better to not use format at all, but use a module that performs conditional table formatting.
Reply
#3
could you provide complete runable snippet with sample format_string and input matrix and desired output

without it, your code is identical to
for input_list in input_matrix:
    formatted_str = format_str.format(*input_list[:len(input_list)])
but almost certainly there is room for improvement.
also note that there is indentation problem in your code
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
Thank you very much for the feedback. Let me clarify the functionality I am after:

Here's the entire function I am working on, which incorporates the code from my earlier post:

def Log_body_writer(input_matrix,input_file,format_str,write_type='a'):
     input_list = []

     if write_type == 'a':
          with open(input_file,'a') as log_file:
               for input_list in input_matrix:
                    list_length = len(input_list)
                    if list_length == 1:
                         formatted_str = format_str.format(input_list[0])
                    elif list_length == 2:
                         formatted_str = format_str.format(input_list[0],input_list[1])
                    elif list_length == 3:
                         formatted_str = format_str.format(input_list[0],input_list[1],input_list[2])
                    elif list_length == 4:
                         formatted_str = format_str.format(input_list[0],input_list[1],input_list[2],input_list[3])
                    elif list_length == 5:
                         formatted_str = format_str.format(input_list[0],input_list[1],input_list[2],input_list[3],input_list[4])
                    elif list_length == 6:
                         formatted_str = format_str.format(input_list[0],input_list[1],input_list[2],input_list[3],input_list[4],input_list[5])
                    elif list_length == 7:
                         formatted_str = format_str.format(input_list[0],input_list[1],input_list[2],input_list[3],input_list[4],input_list[5],input_list[6])
                    elif list_length == 8:
                         formatted_str = format_str.format(input_list[0],input_list[1],input_list[2],input_list[3],input_list[4],input_list[5],input_list[6],input_list[7])
                    log_file.write(formatted_str+'\r\n')
Passed into this function is a matrix (input_matrix). The list lengths of all the lists in the incoming matrix will be the same, so in other words if the list length at matrix element 0 is 3, then that means all the other lists in that matrix will contain exactly 3 elements.

I am also passing into the function a formatted string (format_str). If the lists in the incoming matrix were all 2 elements in length, I would have to pass in one of these 2 element FORMAT strings, or it would break the code:

# Report options
FORMAT_STR1 = "{0:60s}"
FORMAT_STR2 = "{0:16s}{1:>18s}"
FORMAT_STR3 = "{0:20s}{1:26}{2:>18s}"
FORMAT_STR2B = "{0:50s}{1:>20s}"

I'm trying to make this function as flexible as possible, so that it will take in variable length lists and different FORMAT strings. I accomplished that functionality the way I wrote it, but I can't help thinking there has to be more streamlined way of writing this.

Sincere thanks,
C.J.
Reply
#5
so basically you rely on always providing format string with correct number of placeholders. your current code does not handle the possible mismatch between placeholders in format string and number of elements in the input string.
In this case you can just unpack the list
def Log_body_writer(input_matrix,input_file,format_str,write_type='a'):
     if write_type == 'a':
          with open(input_file,'a') as log_file:
               for input_list in input_matrix:
                   formatted_str = format_str.format(*input_list)
                   log_file.write(f'{formatted_str}\r\n')
some thoughts:
no need to initialize input_list to empty list
you can add error handling to handle the case when mismatch between numbers of placeholders and number of elements in the input list
what happens if write type is e.g. 'w'. instead of checking write type in if block, you can just do with open(input_file, write_type) as log_file:
maybe you can add '\r\n` to format string?
look at logging module, if it may suit your needs - probably it will not given that format string may change from call to call
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
Thank you, buran. Your suggestions worked brilliantly!

Thanks,
C.J.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 1,949 Apr-05-2021, 05:40 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020