简体   繁体   中英

How to get the longest string for item in a 2D array/list?

First of all, I would like to apologise that I couldn't mention the topic name well for this question. I was trying to print a table of customer records with the column length and records length will automatically be align perfectly.

customer_list = [["ctm1","jacon","jackson@gmail.com","+60166197213","15/5/1990","jadsfsd23"],["ctm1","jacksonmartin","jacksonmartinez@gmail.com","+60166197213","15/5/1990","jadsfsddfdf23"]]

# show records of customer account info
def view_customer_account():
     # initialize column length
     Ctm_ID_CL, Usrname_CL, Email_CL = 2,8,13
     # loop for longest data length and make it as column length
     # column length will remain as initial column length if longest data length is shorter than it
     for customer in customer_list:
          if len(customer[0]) > Ctm_ID_CL:
               Ctm_ID_CL = len(customer[0])
          if len(customer[1]) > Usrname_CL: 
               Usrname_CL = len(customer[1]) 
          if len(customer[2]) > Email_CL:
               Email_CL = len(customer[2])     
     # print column name
     # column name string will concatenate with a space which multiply with (column length - initial column length)
     print(f'| ID{" "*(Ctm_ID_CL-2)} | Username{" "*(Usrname_CL-8)} | Email Address{" "*(Email_CL-13)} | Phone number | Date of birth |')
     # print records
     # records(str) will concatenate with a space which multiply with (column length/initial column length) - records str length
     for customer in customer_list:
          print(f'| {customer[0]+" "*(Ctm_ID_CL-len(customer[0]))} | {customer[1]+" "*(Usrname_CL-len(customer[1]))} | {customer[2]+" "*(Email_CL-len(customer[2]))} | {customer[3]} | {customer[4]}'+" "*5+"|")

view_customer_account()

However, the way I look for the longest string length for each item in the list and make it as the length of column will get duplicated a lot when there is more field coming in, which is this part:

 # initialize column length
 Ctm_ID_CL, Usrname_CL, Email_CL = 2,8,13
 # loop for longest data length and make it as column length
 # column length will remain as initial column length if longest data length is shorter than it
 for customer in customer_list:
      if len(customer[0]) > Ctm_ID_CL:
           Ctm_ID_CL = len(customer[0])
      if len(customer[1]) > Usrname_CL: 
           Usrname_CL = len(customer[1]) 
      if len(customer[2]) > Email_CL:
           Email_CL = len(customer[2])
      # more fields coming in, will have a lots if else statement

Is there a way to solve this?

I have edited your code and added column_length = [0,0,0,0,0] as a list of column lengths, and use a for loop to assess the lengths. Hope it has achieved your objective.

customer_list = [["ctm1","jacon","jackson@gmail.com","+60166197213","15/5/1990","jadsfsd23"],["ctm1","jacksonmartin","jacksonmartinez@gmail.com","+60166197213","15/5/1990","jadsfsddfdf23"]]

# # show records of customer account info
def view_customer_account():
    # initialize column length
    column_length = [0,0,0,0,0]
    # loop for longest data length and make it as column length
    # column length will remain as initial column length if longest data length is shorter than it
    for customer in customer_list:
        for i in range(5):
            if len(customer[i]) > column_length[i]:
                column_length[i] = len(customer[i])    
    # print column name
    # column name string will concatenate with a space which multiply with (column length - initial column length)
    print(f'| ID{" "*(column_length[0]-2)} | Username{" "*(column_length[1]-8)} | Email Address{" "*(column_length[2]-13)} | Phone{" "*(column_length[3]-5)} | DOB{" "*(column_length[4]-3)} |')
    # print records
    # records(str) will concatenate with a space which multiply with (column length/initial column length) - records str length
    for customer in customer_list:
        print(f'| {customer[0]+" "*(column_length[0]-len(customer[0]))} | {customer[1]+" "*(column_length[1]-len(customer[1]))} | {customer[2]+" "*(column_length[2]-len(customer[2]))} | {customer[3]+" "*(column_length[3]-len(customer[3]))} | {customer[4]+" "*(column_length[4]-len(customer[4]))}'+" |")

view_customer_account()

Output:

| ID   | Username      | Email Address             | Phone        | DOB       |
| ctm1 | jacon         | jackson@gmail.com         | +60166197213 | 15/5/1990 |
| ctm1 | jacksonmartin | jacksonmartinez@gmail.com | +60166197213 | 15/5/1990 |

You could use the tabulate module for this.

from tabulate import tabulate

customer_list = [["ctm1","jacon","jackson@gmail.com","+60166197213","15/5/1990","jadsfsd23"],["ctm1","jacksonmartin","jacksonmartinez@gmail.com","+60166197213","15/5/1990","jadsfsddfdf23"]]

# show records of customer account info
def view_customer_account():
    print(tabulate(customer_list, headers=['ID', 'Username', 'Email Address', 'Phone number', 'Date of birth', 'etc']))

view_customer_account()

results in:

ID    Username       Email Address                Phone number  Date of birth    etc
----  -------------  -------------------------  --------------  ---------------  -------------
ctm1  jacon          jackson@gmail.com            +60166197213  15/5/1990        jadsfsd23
ctm1  jacksonmartin  jacksonmartinez@gmail.com    +60166197213  15/5/1990        jadsfsddfdf23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM