从Python 3中的元组列表中创建一个表 [英] Create a table from a list of tuples in Python 3
本文介绍了从Python 3中的元组列表中创建一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
data = [('Item1',a1,b1,c1,d1, e1,f1),
('Item2',a2,b2,c2,d2,e2,f2),
('Item3',a3,b3,c3,d3,e3,f3)]
我必须打印出这个:
Item1 Item2 Item3
DataA:a1 a2 a3
DataB:b1 b2 b3
DataC:c1 c2 c3
DataD:d1 d2 d3
DataE:e1 e2 e3
DataF:f1 f2 f3
我初始化了一个list:
data_headings = ['','DataA:','DataB','DataC:','DataD:' ,'DataE':,'DataF:']
我的老师也给了我们选择他创建的一个函数:
$ b $ pre $ code $ display $ with $ padding(str)
print({0:< 15}。格式,结束='')
<一些指导如何做到这一点将不胜感激。我一直在玩这个在过去的一天,我仍然无法工作了。
解决方案
def display_with_padding(s):
print({0:< 15}。format,end ='')
def print_row(iterable) :
[display_with_padding(x)for x in iterable]
print()
def main():
data = [
('Item1','a1','b1','c1','d1','e1','f1'),
('Item2','a2','b2','c2' ,'d2','e2','f2'),
('Item3','a3','b3','c3','d3','e3','f3')
]
col_headers = [''] + [x [0] for x in data]#构建标题
print_row(col_headers)
标签= ['DataA:','DataB:','DataC:','DataD:','DataE:','DataF:']
#构建每行
行row_num = []
,枚举中的标签(labels,start = 1):
co
for col in data:
content.append(col [row_num])
rows.append(content)
for row in rows:
print_row(row)
$ b $ if if __name__ =='__main__':
main()
I have homework where I have to take a list containing tuples and print out a table. For example, the list might look like this:
data = [('Item1', a1, b1, c1, d1, e1, f1),
('Item2', a2, b2, c2, d2, e2, f2),
('Item3', a3, b3, c3, d3, e3, f3)]
I would have to print out this:
Item1 Item2 Item3
DataA: a1 a2 a3
DataB: b1 b2 b3
DataC: c1 c2 c3
DataD: d1 d2 d3
DataE: e1 e2 e3
DataF: f1 f2 f3
I have initialised a list:
data_headings = ['','DataA:','DataB','DataC:','DataD:','DataE':,'DataF:']
My teacher has also given us the option to use a function he created:
display_with_padding(str):
print("{0: <15}".format(s), end = '')
Some guidance with how to do this will be much appreciated. I've been playing with this for the past day and I still am unable to work it out.
解决方案
def display_with_padding(s):
print("{0: <15}".format(s), end='')
def print_row(iterable):
[display_with_padding(x) for x in iterable]
print()
def main():
data = [
('Item1', 'a1', 'b1', 'c1', 'd1', 'e1', 'f1'),
('Item2', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2'),
('Item3', 'a3', 'b3', 'c3', 'd3', 'e3', 'f3')
]
col_headers = [''] + [x[0] for x in data] # Build headers
print_row(col_headers)
labels = ['DataA:','DataB:','DataC:','DataD:','DataE:','DataF:']
# Build each row
rows = []
for row_num, label in enumerate(labels, start=1):
content = [label]
for col in data:
content.append(col[row_num])
rows.append(content)
for row in rows:
print_row(row)
if __name__ == '__main__':
main()
这篇关于从Python 3中的元组列表中创建一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文