[英]Create a table from a list of tuples in 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
我已經初始化了一個列表:
data_headings = ['','DataA:','DataB','DataC:','DataD:','DataE':,'DataF:']
我的老師還讓我們選擇使用他創建的函數:
display_with_padding(str):
print("{0: <15}".format(s), end = '')
將不勝感激有關如何執行此操作的一些指導。 過去一天我一直在玩這個,但我仍然無法解決。
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()
訣竅是按某種順序迭代表的每個元素。 先行還是先列?
因為是逐行打印,所以必須先遍歷行,然后在每一列中查找相應的值。 觀察到data
是一個列列表,而第二個列表為每一行提供了一個標簽。 在以下演示中,我已將其重命名為row_labels
。
def display_with_padding(s):
print("{0: <15}".format(s), end = '')
data = [('Item1', 'a1', 'b1', 'c1', 'd1', 'e1', 'f1'),
('Item2', 'a2', 'b2', 'c2', 'd2', 'e2', 'f2'),
('Item3', 'a3', 'b3', 'c3', 'd3', 'e3', 'f3')]
row_labels = ['', 'DataA:', 'DataB:', 'DataC:', 'DataD:', 'DataE:', 'DataF:']
for row_index, label in enumerate(row_labels):
display_with_padding(label)
for column in data:
display_with_padding(column[row_index])
print()
請注意使用enumerate()
在我們迭代row_labels
的同時獲取索引和值。
哦,我修復了您發布的代碼中的一些錯誤。 函數定義存在一些問題(缺少def
和錯誤的參數名稱)以及行標簽中的語法錯誤。 我也重命名了行標簽。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.