栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 字典(数组)格式化写入文本文件或打印

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 字典(数组)格式化写入文本文件或打印

# 字典格式
def write_format_object(obj: dict, tab_num=0, is_tab=1):
    if is_tab:
        data = ("t" * tab_num)
    else:
        data = ''
    data += "{n"
    length = len(obj)
    for key, value in obj.items():
        el_type = type(value)
        length -= 1
        data += ("t" * (tab_num + 1) + f'"{key}":')
        if el_type == int or el_type == float:
            data += f'{value}'
        elif el_type == list or el_type == set or el_type == tuple:
            data += write_format_list(value, tab_num + 1, 0)
        elif el_type == dict:
            data += write_format_object(value, tab_num + 1, 0)
        else:
            data += f'"{value}"'
        if length:
            data += ',n'
        else:
            data += 'n'
    data += ("t" * tab_num) + "}"
    return data

# 列表格式化
def write_format_list(array: list or set or tuple, tab_num=0, is_tab=1):
    array = list(array)
    if is_tab:
        data = ("t" * tab_num)
    else:
        data = ''
    data += "[n"
    length = len(array)
    for index, value in enumerate(array):
        el_type = type(value)
        data += ("t" * (tab_num + 1))
        if el_type == int or el_type == float:
            data += f'{value}'
        elif el_type == list or el_type == set or el_type == tuple:
            data += write_format_list(value, tab_num + 1, 0)
        elif el_type == dict:
            data += write_format_object(value, tab_num + 1, 0)
        else:
            data += f'"{value}"'
        if length != index + 1:
            data += ',n'
        else:
            data += 'n'
    data += ("t" * tab_num) + "]"
    return data

测试

t = {'a': '1232324', 'b': 123456, 'c': 124323.543, 'd': [123123, 'sadffafa', 'fa5', [123123, 'sadffafa', 'fa5', {'e': {'a': '1232324', 'b': 123456, 'c': 124323.543, 'd': [123123, 'sadffafa', 'fa5', [123123, 'sadffafa', 'fa5']]}}]]}
tl = [123123, 'sadffafa', 'fa5']
print(write_format_object(t))
print('n----------------------------n')
print(write_format_list(tl))

输出

{
	"a":"1232324",
	"b":123456,
	"c":124323.543,
	"d":[
		123123,
		"sadffafa",
		"fa5",
		[
			123123,
			"sadffafa",
			"fa5",
			{
				"e":{
					"a":"1232324",
					"b":123456,
					"c":124323.543,
					"d":[
						123123,
						"sadffafa",
						"fa5",
						[
							123123,
							"sadffafa",
							"fa5"
						]
					]
				}
			}
		]
	]
}

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

[
	123123,
	"sadffafa",
	"fa5"
]

进程已结束,退出代码为 0

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/861649.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号