【发布时间】:2016-03-24 00:30:00
【问题描述】:
我有一个包含变量名称和值的字符串。名称和值之间没有指定的分隔符,名称可能包含也可能不包含下划线。
string1 = 'Height_A_B132width_top100.0lengthsimple0.00001'
我想将变量放入字典中:
# desired output: dict1 = {'Height_A_B': 132, 'width_top': 100.0, 'lengthsimple': 0.00001}
尝试下面的itertools方法
输入1:
from itertools import groupby
[''.join(g) for _, g in groupby(string1, str.isdigit)]
输出1:
['Height_A_B', '132', 'width_top', '100', '.', '0', 'lengthsimple', '0', '.', '00001']
以下内容应该差不多了,但是 iPython 解释器告诉我这个 str 属性不存在(它在文档中)。总之……
输入2:
[''.join(g) for _, g in groupby(string1, str.isnumeric)]
输出2:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-25-cf931a137f50> in <module>()
----> 1 [''.join(g) for _, g in groupby(string1, str.isnumeric)]
AttributeError: type object 'str' has no attribute 'isnumeric'
无论如何,如果数字包含带有“+”或“-”符号的指数会怎样?
string2 = 'Height_A132width_top100.0lengthsimple1.34e+003'
# desired output: dict2 = {'Height_A_B': 132, 'width_top': 100.0, 'lengthsimple': 1.34e+003}
输入3:
[''.join(g) for _, g in groupby(string2, str.isdigit)]
输出3:
['Height_A', '132', 'width_top', '100', '.', '0', 'lengthsimple', '1', '.', '34', 'e+', '003']
我想知道,是否有人有一个优雅的解决方案?
更新: 下面有一些关于保留数值变量类型(例如 int、float 等)的讨论。事实上,string2 中的科学记数法有点像红鲱鱼,因为如果你创建一个变量
>>> a = 1.34e+003
你得到
>>> print a
1340.0
无论如何,所以产生一个包含 1.34+003 的字符串的机会很低。
所以 string2 是一个更合适的测试用例,如果我们将其更改为,比如说
string2 = 'Height_A132width_top100.0lengthsimple1.34e+99'
【问题讨论】:
-
我怀疑是否有一个优雅的解决方案,因为输入数据的不优雅。 :)
-
@PM2Ring 哦,亲爱的 :) 真的很痛……
标签: python string python-2.7 dictionary split