如何从原始数据字符串创建字典

Lan*_*ana 4 python

基本上我需要从一串数据创建一个字典

鉴于:

data = "electron1, gamma5, proton43, boson98, ..."
Run Code Online (Sandbox Code Playgroud)

d(data) 会导致:

{'electron':1, 'gamma':5, 'proton':43, 'boson':98, ...}
Run Code Online (Sandbox Code Playgroud)

我当前的代码显示"基数10 ..."的错误消息

def d(n):
        pair = dict()
        for i in range(0,n):
                word = input().split()
                key = word[0]
                value = word[1]
                pair[key]=value
        print(pair)

n = int(input())          
d ={}                     
for i in range(n):        
    text = input().split()
    d[text[0]] = text[1]
print(d)
Run Code Online (Sandbox Code Playgroud)

Ste*_*uch 8

您可以使用正则表达式和生成器表达式执行此操作,如:

码:

END_NUMS_RE = re.compile(r'^(\D+)(\d+)$')
dict(END_NUMS_RE.match(x.strip()).groups() for x in data.split(','))
Run Code Online (Sandbox Code Playgroud)

测试代码:

import re
END_NUMS_RE = re.compile(r'^(\D+)(\d+)$')
data = "electron1, gamma5, proton43, boson98"
print(dict(END_NUMS_RE.match(x.strip()).groups() for x in data.split(',')))
Run Code Online (Sandbox Code Playgroud)

结果:

{'electron': '1', 'gamma': '5', 'proton': '43', 'boson': '98'}
Run Code Online (Sandbox Code Playgroud)

但!正则表达式:

对于那些担心使用正则表达式的人:

让我们来一个正则表达式的答案与第二个最多投票的答案:

import re
END_NUMS_RE = re.compile(r'^(\D+)(\d+)$')
data = "electron1, gamma5, proton43, boson98"

def method1():
    return dict(END_NUMS_RE.match(x.strip()).groups()
                for x in data.split(','))

def method2():
    l = data.split(',')
    return {
        ''.join(
            [x for x in item if not x.isdigit()]):
            int(''.join([x for x in item if x.isdigit()])) for item in l
    }


from timeit import timeit
print(timeit(method1, number=10000))
print(timeit(method2, number=10000))
Run Code Online (Sandbox Code Playgroud)

时间结果:

0.05789754982012146
0.10536237238963242
Run Code Online (Sandbox Code Playgroud)

正则表达式的答案速度是原来的两倍.


Bit*_*han 6

没有重新的方法

Data = "electron1, gamma5, proton43, boson98"
l=Data.split(',')
d={''.join([x for x in item if not x.isdigit()]):int(''.join([x for x in item if x.isdigit()])) for item in l}
print(d)
Run Code Online (Sandbox Code Playgroud)

产量

{'electron': 1, ' gamma': 5, ' proton': 43, ' boson': 98}
Run Code Online (Sandbox Code Playgroud)