[英]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.