문자열의 형식은 "a:1 b:2 c:x d:2.13e-5"
과 비슷합니다. 파이썬 dict로 변환 할 수있는 방법이 있습니까?파이썬은 dict에 paritcular 문자열을 변환합니다
-------------- 편집 라인 --------------
은 큰 응답에 따르면, 내가 ipython에 (여러 가지 방법을 시도) :
In [6]: import re
In [7]: %paste
def f1(line):
item_dict = {}
for item in line.split():
kv = item.split(':')
item_dict[kv[0]] = kv[1]
def f2(line):
item_dict = {}
item_pat = re.compile(r'(\w+):(.+)')
for item in line.split():
m_res = item_pat.match(item)
item_dict[m_res.group(1)] = m_res.group(2)
def f3(line):
dict(item.split(':') for item in line.split())
## -- End pasted text --
In [8]: line = 'a:1 b:3243 dsfds:4323llsjdf \t fdsf:3232l'
In [9]: %timeit f1(line)
100000 loops, best of 3: 3.99 us per loop
In [10]: %timeit f2(line)
100000 loops, best of 3: 8.83 us per loop
In [11]: %timeit f3(line)
100000 loops, best of 3: 5.19 us per loop
빠른 것 같다, 그러나 수백만 번 호출 있기 때문에 내 응용 프로그램에서, 여전히 모든 (약 30 %) 많은 시간을 사용 f1()
첫 번째 방법.
더 효과적인 방법이 있습니까? 또는 cython
? 이 split
는 값의 int 있습니까, 문자열, 수레, 또는 이들의 모든 엉망? – jozzas
python이 변수 유형을 추측하기를 기대합니까? – jamylak