-1

我正在尝试用这个字符串创建一个值的字典

'idle (images=green:200, inpadoc=green:60, other=green:1000, retrieval=green:200, search=green:30)'

输出:

{'images':['green', 200], 'inpadoc':['green', 60],...}

什么是最好的通用解决方案?

谢谢!

4

5 回答 5

1

请试试这个:

def main():
    x = 'idle (images=green:200, inpadoc=green:60, other=green:1000, retrieval=green:200, search=green:30)'
    x= x.replace("idle (", "")
    x= x.replace(")", "")
    tmp = x.split(',')

    tmp2 = dict( i.split('=') for i in tmp )

    for item in tmp2:        
        tmp2[item] = tmp2[item].split(":")

    print tmp2  


if __name__ == '__main__':
    main()
于 2013-09-02T08:52:18.677 回答
0

首先移除'ìdle ('钻头。然后分裂', ',然后分裂'=',然后分裂':'

于 2013-09-02T08:40:46.043 回答
0
str = 'idle (images=green:200, inpadoc=green:60, other=green:1000, retrieval=green:200, search=green:30'
str = str.split('(')[1]
dict = {}
for sublist in str.split(','):
    split1 = sublist.split('=')
    split2 = split1[1].split(':')
    dict[split1[0]] = [split2[0],int(split2[1])]

print dict

输出

{'images': ['green', 200], ' other': ['green', 1000], ' search': ['green', 30], ' retrieval': ['green', 200], ' inpadoc': ['green', 60]}
于 2013-09-02T08:46:42.637 回答
0

你可以使用这个:

# Get rid of unwanted part of the string
text='idle (images=green:200, inpadoc=green:60, other=green:1000, retrieval=green:200, search=green:30)'
text = text[text.find(' ')+1:].strip('()')

# Define the converter function
def converter(string):
    [key,value] = string.split('=') # Split into ['images','green:200']
    value = value.split(':') # Split into ['images',['green','200']]
    value[1] = int(value[1]) # Convert the number into int ['images',['green':200]]
    return [key,value]

print dict(map(converter,text.split(', ')))

所以首先,你摆脱了“空闲”和括号。

然后定义将每个条目 ( images=green:200) 转换为二元素列表 ( ) 的函数,该列表将使用该函数['images',['green',200]]自动转换为字典。dict

使用map函数比只遍​​历列表要快,这就是 Python 的美妙之处。

编辑:

糟糕,显然使用这个map函数并不比简单地遍历列表更快。

import time
startTime = time.time()
for i in range(100000):
    dict(map(converter,text.split(', ')))
print 'Done in %.3fs' % (time.time()-startTime)
# Done in 1.703s

startTime = time.time()
for i in range(100000):
    result = {}
    for element in text.split(', '):
        [key,value] = element.split('=')
        value = value.split(':')
        value[1] = int(value[1])
        result[key] = value
print 'Done in %.3fs' % (time.time()-startTime)
# Done in 1.405s

但是您可以选择。=D

于 2013-09-02T08:49:13.690 回答
0
original = 'images=green:200,inpadoc=green:60,other=green:1000,retrieval=green:200,search=green:30'
parsed = {}
for e in original.split(','):
    split = e.split('=')
    parsed[split[0]] = split[1].split(':')

我希望这对你来说足够可读。这个解决方案与我之前所有这些人给出的解决方案相似,但它仍然是一个有趣的茶歇练习:)

于 2013-09-02T09:19:44.673 回答