繁体   English   中英

如何获得一个函数来返回python中表的每一行?

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

我正在构建一个简单的函数,它调用一个元组列表并以表格的形式返回一个字符串。 我不确定如何生成表格的每一行。 这是我几个月前开始编码以来一直在努力解决的问题。

我的任务:拿一个年龄列表说 [20, 33, 99, 6, 21] 并生成下表:

不。 年龄 团体
1 20 青年 (20-29)
2 33 成人 (30-44)
3 99 很老 (81+)
4 6 儿童 (6-12)
5 21 青年 (20-29)

这是我的模块中的功能:

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)

我可以使用以下命令打印脚本中的每一行:

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)

我觉得在脚本中调用打印时存在冗余,而在模块内的函数中调用它。 无论如何,我确信有一些简单的方法可以做到这一点,但我似乎无法理解这个想法。 帮助将不胜感激!

我相信我自己解决了这个问题并且它有效。 我只是忘记启动一个空列表并为每一行使用一个累加器。 这是新的函数代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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