我需要找到最快的方法来标记信号。信号的形式为:
identifier:value identifier:value identifier:value ...
标识符
仅由字母数字和下划线组成。 identifier
用空格与先前的值分隔。值可能包含字母数字、各种大括号/方括号和空格。
例如
signal_id:debug_word12_ind 数据:{ } virtual_interface_index:0x0000 module_id:0x0001 module_sub_id:0x0016 时间戳:0xcc557366 debug_words:[0x0006 0x0006 0x0000 0x0000 0x0000 0x0000 0xcc55 0x70 a9 0x4c55 0x7364 0x0000 0x0000] 序列号:0x0174
我想出的最好的如下。理想情况下,我希望将所需时间减半。我已经尝试过使用正则表达式的各种方法,但它们并没有更好。有什么建议吗?
# Convert data to dictionary. Expect data to be something like
# parameter_1:a b c d parameter_2:false parameter_3:0xabcd parameter_4:-56
# Split at colons. First part will be just parameter name, last will be just value
# everything in between will be <parameter name><space><value>
parts1 = data.split(":")
parts2 = []
for part in parts1:
# Copy first and last 'as is'
if part in (parts1[0], parts1[-1]):
parts2.append(part)
# Split everything in between at last space (don't expect parameter names to contain spaces)
else:
parts2.extend(part.rsplit(' ', 1))
# Expect to now have [parameter name, value, parameter name, value, ...]. Convert to a dict
self.data_dict = {}
for i in range(0, len(parts2), 2):
self.data_dict[parts2[i]] = parts2[i + 1]
最佳答案
我对您的解决方案进行了一些优化:
1) 从循环中删除了检查。
2) 更改了字典创建代码:Pairs from single list .
parts1 = data.split(":")
parts2 = []
parts2.append(parts1.pop(0))
for part in parts1[0:-1]:
parts2.extend(part.rsplit(' ', 1))
parts2.append(parts1.pop())
data_dict = {k : v for k, v in zip(parts2[::2], parts2[1::2])}
关于python - 标记信号的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58240302/