簡體   English   中英

Python將旁串轉換為字典

[英]Python convert a paritcular string to dict

字符串的格式類似於"a:1 b:2 c:xd:2.13e-5" ,是否有某種方法可以快速,簡單地將其轉換為python dict?

--------------編輯行--------------

根據很好的答案,我嘗試了幾種方法(在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

第一種方法f1()似乎更快,但是在我的應用程序中,它仍然使用很多時間(約占總數的30%),因為它被調用了數百萬次。

有沒有更有效的方法? 還是cython

>>> s = "a:1 b:2 c:x d:2.13e-5"
>>> dict( p.split(':') for p in s.split(' ') )
{'a': '1', 'c': 'x', 'b': '2', 'd': '2.13e-5'}

此操作首先將字符串split為空格,以獲取鍵值對( p )。 然后,將每個對用“:”分隔,以產生要添加到字典中的每個鍵/值。

請注意,未進行任何轉換。 所有鍵/值仍然是字符串。 為了做得更好,您將需要一個稍微聰明的函數,該函數會將任何輸入字符串轉換為您期望的類型。

import ast

def guess(s):
    try:
        return ast.literal_eval(s)
    except ValueError:
        return s    

s = "a:1 b:2 c:x d:2.13e-5"
print dict(map(guess, x.split(':')) for x in s.split())

{'a': 1, 'c': 'x', 'b': 2, 'd': 2.13e-05}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM