この文字列から値の辞書を作成しようとしています
'idle (images=green:200, inpadoc=green:60, other=green:1000, retrieval=green:200, search=green:30)'
出力:
{'images':['green', 200], 'inpadoc':['green', 60],...}
最善の一般的な解決策は何ですか?
ありがとう!
この文字列から値の辞書を作成しようとしています
'idle (images=green:200, inpadoc=green:60, other=green:1000, retrieval=green:200, search=green:30)'
出力:
{'images':['green', 200], 'inpadoc':['green', 60],...}
最善の一般的な解決策は何ですか?
ありがとう!
まずは'ìdle ('
ビットを外します。次に で分割し', '
、次に で分割し'='
、次に で分割し':'
ます。
これを使用できます:
# 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(', ')))
まず、「idle」と括弧を取り除きます。
次に、各エントリ ( images=green:200
) を 2 要素リスト ( ['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