二维表格格式Python

2024-05-16 23:16:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从我在字典中存储的数据创建一个2D表格格式。

示例:

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是行标签,experistx是列名。 如果数据集的列名没有值,则应添加空字符串作为占位符。

有人能帮忙吗?python中有什么现成的格式,我可以使用吗?


Tags: 数据示例字典格式标签表格id3id2
1条回答
网友
1楼 · 发布于 2024-05-16 23:16:17

一个快速而肮脏的实现(修复问题中的拼写错误…)

d = {'ID1':[('Experiment1', 40), ('Experiment2', 59), ('Experiment3', 65)],    
 'ID2':[('Experiment1', 68), ('Experiment2', 21), ('Experiment3', 39)],   
 'ID3':[('Experiment1', 57), ('Experiment2', 15), ('Experiment4', 99)]}

COLUMN_WIDTH = 20
STRING_WHEN_MISSING = '""'
PADDING_STRING = "."


#first determine what are the columns - from the first line
columns = ["id"] #there is always at least the id column
columns = columns + [colName for (colName, colValue) in d.items()[0][1]]

print "".join([ col.ljust(COLUMN_WIDTH) for col in columns])

#browse the lines, order by ID Ascending
for (rowId, rowValues) in sorted(d.items(), key= lambda x: x[0].lower()):
    #print rowId
    #print rowValues
    rowValuesDict = dict(rowValues) #make it a dict with access by key
    rowValuesDict["id"] = rowId
    #print rowValuesDict
    print "".join([ str(rowValuesDict.get(col, STRING_WHEN_MISSING)).ljust(COLUMN_WIDTH, PADDING_STRING) for col in columns])

打印出来:

id                  Experiment1         Experiment2         Experiment3         
ID1.................40..................59..................65..................
ID2.................68..................21..................39..................
ID3.................57..................15..................""..................

注:

你的原始字典格式有点奇怪。。。我期待更多这样的事情:

d = [('ID1',{'Experiment1': 40, 'Experiment2':59, 'Experiment3':65}),    
     ('ID2',{'Experiment1': 68, 'Experiment2':21, 'Experiment3':39})] 

一些评论:

对于这种情况,您需要阅读一些Python字符串方法:center(), ljust() and rjust(),这些方法在字符串之前和/或之后添加字符以强制其总宽度。

显然,这个想法主要是通过列表/字典循环并提取值。

注意dict方法get()的使用,该方法允许在给定键不存在值时具有默认值。

相关问题 更多 >