繁体   English   中英

用字典理解将字符串解析成字典的pythonic方法

[英]pythonic way of parsing a string into a dictionary with dict comprehension

对于给定的字符串

key = "test: abc :bcd,ef:1923:g, x : y : z\nkey2 :1st:second\n  etc :values:2,3,4:..."

我想解析字符串以将第一个标记作为键存储到字典中,并将 rest 元素作为值列表,类似于以下结果:

{'test': ['abc', 'bcd,ef', '1923', 'g, x', 'y', 'z'], 'key2': ['1st', 'second'], 'etc': ['values', '2,3,4', '...']}

我有


def parseLine(line):
    return list(map(str.strip, line.split(":")))

result = {parseLine(line)[0]:parseLine(line)[1:] for line in str_txt.split('\n')}
print(result)

但是在 dict 理解的表达式中,调用 function parseLine 两次以将 dict 的键和值设置为parseLine(line)[0]:parseLine(line)[1:]

有没有更好的方法来重写 dict 理解?

{lst[0]:lst[1:] for lst in map(lambda s: list(map(str.strip, s.split(":"))), key.split('\n'))}

它给:

{'test': ['abc', 'bcd,ef', '1923', 'g, x', 'y', 'z'],
 'key2': ['1st', 'second'],
 'etc': ['values', '2,3,4', '...']}

您可以在推导式中使用map来应用 function,然后对结果进行解构。

result = {k: v for k, *v in map(parseLine, str_txt.split('\n'))}

另请注意,如果您仅为此使用parseLine ,则可以在不转换为list的情况下对其进行重写:

def parseLine(line):
    return map(str.strip, line.split(":"))
import re

s = "test: abc :bcd,ef:1923:g, x : y : z\nkey2 :1st:second\n  etc :values:2,3,4:..."

s = re.sub(r'[^a-z0-9,]',' ',s)

print ({ x.split()[0]:x.split()[1:] for x in s.split("\n") })

Output:

{'test': ['abc', 'bcd,ef', '1923', 'g,', 'x', 'y', 'z'], 'key2': ['1st', 'second'], 'etc': ['values', '2,3,4']}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM