将字符串变量读入变量

2024-04-24 23:15:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三个关键字%vel%note%blah,我想把它们从字符串解析成整数:

s = "%vel=127, %note=64,     %blah=13"

# should give { 'vel': 127, 'note': 64,  'blah': 13}
# or vel = 127 // note = 64 //  blah = 13

或者

s = "%blah=5,%note=44"
# should give { 'blah': 5, 'note': 44} 

我做过这样的事情:

s = "%vel=127, %note=64,     %blah=13"
d = dict()
for k in s.split(','):
    k = k.strip()
    if "%vel" in k: d['vel'] = int(k.split("%vel=")[1])
    if "%note" in k: d['note'] = int(k.split("%note=")[1])
    if "%blah" in k: d['blah'] = int(k.split("%blah=")[1])
print d

它管用,但我觉得很难看。你知道吗

如何以更好的方式/Python式的方式进行?


Tags: or字符串inif方式整数关键字事情
3条回答

快速列表理解示例:

s = "%blah=5, %note=44"
print dict([item.split('=') for item in s.replace(' ','').replace('%', '').split(',')])

编辑:

s = "%blah=5, %note=44"
# existing dict
old_dict_with_data = { ... }     
result = dict(map(lambda x: [x[0], int(x[1])], [item.split('=') for item in s.replace(' ', '').replace('%', '').split(',')]))
old_dict_with_data.update(result)

我建议把这些理解的东西分成几个操作,因为我承认它看起来不太可读:(

请随便填写,我会解释的

使用正则表达式非常容易:

示例:

>>> from re import findall
>>> s = "%vel=127, %note=64,     %blah=13"
>>> m = findall("%([a-z]+)=([0-9]+)", s)
>>> d = dict(m)
>>> d
{'note': '64', 'blah': '13', 'vel': '127'}

您甚至可以将整数值转换为适当的int(s):

>>> dict((k, int(v)) for k, v in m)
{'note': 64, 'blah': 13, 'vel': 127}

不知道为什么没人在查字典。你知道吗

>>> s = "%blah=5, %note=44"
>>> {k: int(v) for k, v in (item[1:].split('=') for item in s.split(', '))}
{'note': 44, 'blah': 5}

编辑:对于格式错误的情况:

>>> s = "%vel=127, %note=64,     %blah=13"
>>> {k: int(v) for k, v in (item.strip()[1:].split('=') for item in s.split(','))}
{'vel': 127, 'note': 64, 'blah': 13}

相关问题 更多 >