[英]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:我的任务:拿一个年龄列表说 [20, 33, 99, 6, 21] 并生成下表:
No.不。 | Age年龄 | Group团体 |
---|---|---|
1 1 | 20 20 | Young Adult (20-29)青年 (20-29) |
2 2 | 33 33 | Adult (30-44)成人 (30-44) |
3 3 | 99 99 | Very Old (81+)很老 (81+) |
4 4 | 6 6 | Child (6-12)儿童 (6-12) |
5 5 | 21 21 | Young Adult (20-29)青年 (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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.