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


Messages In This Thread
Looking for a sleeker way to code this function - by CJHUND - Aug-11-2020, 03:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Putting code into a function breaks its functionality, though the code is identical! PCesarano 1 2,021 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