Skip to content

Instantly share code, notes, and snippets.

@bao-qian
Forked from JeffreyZhao/打印表头.md
Created March 23, 2016 03:34
Show Gist options
  • Select an option

  • Save bao-qian/0f241406225d676a6a64 to your computer and use it in GitHub Desktop.

Select an option

Save bao-qian/0f241406225d676a6a64 to your computer and use it in GitHub Desktop.

打印表头

小明正在用JavaScript写一个日志分析程序。该程序会将日志转化为CSV文件,以便在Excel等应用中加载为一个表格。现在他在生成表头上遇到了困难。

他需要实现如下一个方法:

function printLine(array) {
    console.log(array.join(","));
}

function printHeader(obj) {
	/* 使用 printLine 输出内容*/
}

输入

小明获取一个对象,需要根据这个对象的结构生成表头。例如:

{
	Process: {
		CpuUsage: 0
		VirtualMemory: 0,
		PrivateMemory: 0
	},
	Subscriptions: {
		Order: {
			TotalCount: 0,
			LastMinute: 0,
			Failed: 0
		},
		User: {
			TotalCount: 0
			LastMinute: 0
		}
	}
}

由于表头仅和对象结构相关,因此无需关注字段的值。

输出

输出为一行至多行文本,为CSV格式,字段之间以逗号隔开(简化问题起见,字段本身不包含逗号)。

如上输入,则需要得到以下输出:

Process,,,Subscriptions
CpuUsage,VirtualMemory,PrivateMemory,Order,,,User
,,,TotalCount,LastMinute,Failed,TotalCount,LastMinute

该CSV文件内容使用Excel打开便会得到以下表格(请忽略格式):

ProcessSubscriptions
CpuUsageVirtualMemoryPrivateMemoryOrderUser
TotalCountLastMinuteFailedTotalCount LastMinute

总而言之,是将对象结构转化为如上表头。

@bao-qian
Copy link
Author

from collections import OrderedDict


def print_line(line: list):
    print(','.join(line))


def print_header(header_dict: dict):
    table = []
    width = 0

    def create_table(h=header_dict, height=0):
        nonlocal width

        for key in h:
            if len(table) <= height:
                table.append([])
            n = width - len(table[height])
            table[height] += [''] * n
            table[height].append(key)

            if type(h[key]) is OrderedDict:
                create_table(h[key], height + 1)

        width = max(len(table[height]), width)

    create_table()
    for line in table:
        print_line(line)


if __name__ == '__main__':
    HEADER_DICT = OrderedDict([
        ('Process', OrderedDict([
            ('CpuUsage', 0),
            ('VirtualMemory', 0),
            ('PrivateMemory', 0)
        ])),
        ('Subscriptions', OrderedDict([
            ('Order', OrderedDict([
                ('TotalCount', 0),
                ('LastMinute', 0),
                ('Failed', 0)
            ])),
            ('User', OrderedDict([
                ('TotalCount', 0),
                ('LastMinute', 0)
            ]))
        ]))]
    )
    print_header(HEADER_DICT)

python 版。对象的建立是扒的楼上 chenshuo 的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment