gpt4 book ai didi

Python-原始文本到字典列表

转载 作者:行者123 更新时间:2023-12-01 01:04:38 24 4
gpt4 key购买 nike

我有以下字符串需要转换为字典列表。

'"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018"," 23.19"," 2.13"," 1.32":"08-Jan-2019"," 22.70"," 5.22"," 1.02":'

执行此操作的 Pythonic 方法是什么?键为 "Date","Volume/Length","Length/Width","Weight gm"

最佳答案

首先,将字符串转换为嵌套的 list,其中每个内部 list 代表一行:

import re

string = '"Date","Volume/Length","Length/Width","Weight gm":"08-Dec-2018"," 23.19"," 2.13"," 1.32":"08-Jan-2019"," 22.70"," 5.22"," 1.02":'

nested_list = [[value.strip() for value in row.replace('"', '').split(',')] for row in string.strip(':').split(':')]

# Colons divide rows, so there shouldn't be any at the ends

然后转置嵌套的列表,以便每个内部列表现在代表一个。每列中的第一个元素是列名称,其余元素是该列中的值。根据这个模式,我们可以执行切片来获取最终 dict 的键值对:

transposed_list = list(zip(*nested_list))
result = {column[0]: column[1:] for column in transposed_list}

# This part can be changed to list(column[1:]) if you want the inner elements to be lists

print(result)

输出:

{'Date': ('08-Dec-2018', '08-Jan-2019'), 
'Volume/Length': ('23.19', '22.70'),
'Length/Width': ('2.13', '5.22'),
'Weight gm': ('1.32', '1.02')}

关于Python-原始文本到字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55486456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com