簡體   English   中英

垂直格式化表格中的多個列表列表

[英]format multiple list of lists in a table vertically

我不熟悉格式化並嘗試將多個列表列表格式化為整潔。 我嘗試過的用於單個列表列表的代碼是:

from tabulate import tabulate

orig = [['all', 4], ['away', 1], ['ball', 0], ['before', 1]]
first = [['every', 5], ['home', 1], ['game', 2], ['time', 2]]
second = [['one', 7], ['family', 1], ['sport', 3], ['now', 3]]
third = [['day', 10], ['friends', 1], ['game', 8], ['never', 3]]

print(tabulate([orig, first, second, third],  headers=['Orig', 'First', 'Second', 'Third']))

我遇到的問題是行和列顛倒了。

例如,我想 Orig 是 ['all', 4],['away', 1],['ball', 0],['before', 1]

任何幫助將不勝感激公司。 其他想法。

提前致謝

你必須轉置表格。 一種方法是使用zip

print(
    tabulate(
        zip(orig, first, second, third),
        headers=['Orig', 'First', 'Second', 'Third']
    )
)

結果:

Orig           First         Second         Third
-------------  ------------  -------------  --------------
['all', 4]     ['every', 5]  ['one', 7]     ['day', 10]
['away', 1]    ['home', 1]   ['family', 1]  ['friends', 1]
['ball', 0]    ['game', 2]   ['sport', 3]   ['game', 8]
['before', 1]  ['time', 2]   ['now', 3]     ['never', 3]

你不能只用字典嗎?

orig = {"all": 4, "away": 1, "ball": 0, "before": 1}

# Keep in mind that to get the values you use the key. so:
# orig["all"] would give you 4
# iterating is also different
for key in orig:
    print(key, orig[key])
# this will give you the key and the value.

我希望這對你有幫助,雖然不確定這是否適用於你的具體情況,但你可以試試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM