二维表格格式 Python
我想根据存储在字典中的数据创建二维表格式。
示例:
d = {'ID1':[('Experiment1', 40), (Experiment2, 59), (Experiment3, 65)],
'ID2':[('Experiment1', 68), (Experiment2, 21), (Experiment3, 39)],
'ID3':[('Experiment1', 57), (Experiment2, 15), (Experiment4, 99)]}
应给出下表:
Experiment1 Experiment2 Experiment3 Experiment4
ID1 ...40.................................59.... ......................................65...................... …………''
ID2....68.................................21....... ......................................39........................................ ...''
ID3....57.................................15....... ……………………………… ......99
其中 IDx 是行标签,Experimentx 是列名称。 如果数据集的列名称没有值,则应添加一个空字符串作为占位符。
有人可以帮助如何做到这一点吗? python中有没有现成的格式可供我使用?
I want to create a 2D table format from my data stored in a dictionary.
Example:
d = {'ID1':[('Experiment1', 40), (Experiment2, 59), (Experiment3, 65)],
'ID2':[('Experiment1', 68), (Experiment2, 21), (Experiment3, 39)],
'ID3':[('Experiment1', 57), (Experiment2, 15), (Experiment4, 99)]}
Should give the following table:
Experiment1 Experiment2 Experiment3 Experiment4
ID1 ...40................................59...............................65................................''
ID2....68...............................21................................39................................''
ID3....57...............................15................................''..................................99
Where IDx are the row labels and Experimentx are the column names.
If a dataset don't have a value to the column name, then an empty string should be added as placeholder.
Can anybody help how to do this? Is there any ready format in python, which I could use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个快速而肮脏的实现(修复问题中的拼写错误......)
这会打印出:
注意:
你的原始字典的格式有点奇怪......我希望有更多这样的东西:
一些评论:
对于这种类型事情,你想阅读一些Python字符串方法:center(), ljust()和 rjust()在字符串之前和/或之后添加字符以强制其总宽度。
除此之外,这个想法主要是关于循环列表/字典并提取值。
注意 dict 方法 get() 的使用,它允许有一个默认值当给定键不存在值时的值。
A quick and dirty implementation (fixing your typos in the question ...)
This prints out :
Note :
The format of your orginal dictionary is a bit strange ... I would expect more something like this :
Some Comments:
For this kind of things, you want to read about some Python string methods : center(), ljust() and rjust() that add characters before and/or after a string to force its total width.
Appart from that, the idea is mostly about looping through lists/dictionaries and extract value.
Note the use of dict method get() that allows to have a default value when no value exists for a given key.