亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何將輸出變成表格?

我如何將輸出變成表格?

九州編程 2022-06-28 15:40:46
我希望輸出是表格。沒有大括號和雙引號。我能得到一些幫助嗎?我正在使用 python 3.7.5students = [   { "grade": 5,    "firstname": "Brendon",     "lastname": "Urie",     "gender": "M"     },  {     "grade": 7,    "firstname": "Freddy",    "lastname": "Mercury",    "gender": "M"   },  {     "grade": 12,    "firstname": "Tessa",    "lastname": "Thompson"  }]output("list", students, None)
查看完整描述

3 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

您可以使用 pandas 將其打印為數據框。


import pandas as pd


students = [ 

    { 

        "grade":5,

        "firstname":"Brendon",

        "lastname":"Urie",

        "gender":"M"

    },

    { 

        "grade":7,

        "firstname":"Freddy",

        "lastname":"Mercury",

        "gender":"M"

    },

    { 

        "grade":12,

        "firstname":"Tessa",

        "lastname":"Thompson"

    }

]


df = pd.DataFrame(students)

df

結果是:


    firstname   gender  grade   lastname

0   Brendon M   5   Urie

1   Freddy  M   7   Mercury

2   Tessa   NaN 12  Thompson


查看完整回答
反對 回復 2022-06-28
?
MYYA

TA貢獻1868條經驗 獲得超4個贊

您可以使用表格將字典漂亮地打印為表格


from tabulate import tabulate


def dict_to_list(lst):

  """ Converts students to list of the form 

[[5, 'Brendon', 'Urie', 'M'], [7, 'Freddy', 'Mercury', 'M'], ...] """

  return [[v for v in d.values()] for d in lst]


students = [ 

  { "grade": 5,

    "firstname": "Brendon", 

    "lastname": "Urie", 

    "gender": "M" 

    },

  { 

    "grade": 7,

    "firstname": "Freddy",

    "lastname": "Mercury",

    "gender": "M" 

  },

  { 

    "grade": 12,

    "firstname": "Tessa",

    "lastname": "Thompson"

  }

]


# tabulate takes as input: list of lists, and header

# list of list = dict_to_list(students)

# header = students[0].keys()

print (tabulate(dict_to_list(students), students[0].keys()))

輸出(列對齊的漂亮格式)


 grade  firstname    lastname    gender

-------  -----------  ----------  --------

      5  Brendon      Urie        M

      7  Freddy       Mercury     M

     12  Tessa        Thompson


查看完整回答
反對 回復 2022-06-28
?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

如果您的意思是終端表terminaltables正是您所需要的:

https://robpol86.github.io/terminaltables/


查看完整回答
反對 回復 2022-06-28
  • 3 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號