有时,我们可能不得不将字符串内容转换为字典。该字符串可能具有特定的格式,可以进行键值转换。这种类型的问题在机器学习领域很常见。让我们讨论解决这个问题的某些方法。
以下程序代码均在Win7+Python3.8环境下测试。
方法1:split()+字典推导式
该组合方法可用于执行此特定任务。分为两步,在第一步中,使用 split 将字符串转换为列表,然后使用字典推导式将其转换回字典。
>>> test_str = "Cfg = 1,Good = 2, CS = 3, Portal = 4"
>>> test_str
'Cfg = 1,Good = 2, CS = 3, Portal = 4'
>>> res = {key:int(val) for key, val in (item.split('=') for item in test_str.split(',')) }
>>> res
{'Cfg ': 1, 'Good ': 2, ' CS ': 3, ' Portal ': 4}

方法2:eval()
这个特殊问题可以使用内置函数 eval 解决,该函数在内部评估字符串并根据条件将字符串转换为字典。
>>> test_str = "Cfg = 1, Good = 2, CS = 3, Portal = 4"
>>> test_str
'Cfg = 1, Good = 2, CS = 3, Portal = 4'
>>> res = eval('dict(%s)'%test_str)
>>> res
{'Cfg': 1, 'Good': 2, 'CS': 3, 'Portal': 4}

方法3:使用split()+index()+切片
>>> test_str = "Cfg = 1, Good = 2, CS = 3, Portal = 4"
>>> test_str
'Cfg = 1, Good = 2, CS = 3, Portal = 4'
>>> res = dict()
>>> x = test_str.split(',')
>>> for i in x:
... a = i[:i.index("=")]
... b = i[i.index("=") + 1:]
... res[a] = b
...
>>> res
{'Cfg ': ' 1', ' Good ': ' 2', ' CS ': ' 3', ' Portal ': ' 4'}

本文根据python-converting-string-content-to-dictionary翻译而来,不代表烟海拾贝立场,如若转载,请注明出处:https://somirror.com/3339.html