简体   繁体   中英

How can I get a function to return each row of a table in python?

I am building a simple function which calls in a list of tuples and returns a string in the form of a table. I am not sure how I can generate each new row of a table. This is something that I've been struggling with since I started coding a few months ago.

My task: Take a list of ages say [20, 33, 99, 6, 21] and generate the following table:

No. Age Group
1 20 Young Adult (20-29)
2 33 Adult (30-44)
3 99 Very Old (81+)
4 6 Child (6-12)
5 21 Young Adult (20-29)

Here is my function in my module:

def get_table(age_tuple: list) -> str:
    """Accepts a list of tuples (age, index) where the index refers to the age
    group in the get_groups() function."""
    group_id = get_groups()
    for ndx in range(len(age_tuple)):
        age = age_tuple[ndx][0]
        index = age_tuple[ndx][1]
        group = group_id[index]
        table_rows = str(ndx + 1).ljust(5) + str(age).ljust(5) + group
        print(table_rows)

I can get it to print each of the rows in my script using:

import age_analyze

ages = [20, 33, 99, 6, 21]
#age_list = age_analyze.get_age_tuples(ages)

my_list = age_analyze.get_age_tuples(ages)
table = age_analyze.get_table(my_list)

print(table)

By I feel like there is redundancy in calling print in the scrip while it has been called in the function within the module. Anyway, I'm sure there are easy ways of doing this but I cannot seem to get my head wrapped around this idea. Help would be appreciated!

I believe I sorted this out on my own and it works. I simply forgot to start an empty list and use an accumulator for each row. Here is the new function code:

def get_table(age_tuple: list) -> str:
    group_id = get_groups()
    table_rows = "#".ljust(5) + "Age".ljust(5) + "Group" +"\n"
    for ndx in range(len(age_tuple)):
        age = age_tuple[ndx][0]
        index = age_tuple[ndx][1]
        group = group_id[index]
        table_rows += str(ndx + 1).ljust(5) + str(age).ljust(5) + group +"\n"
    return table_rows

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