我正在尝试将列表拆分成具有多个键和相应值的字典。我不确定这是否可能。但基本上,我试图解析一个列表,并基于某些条件,我想将以下各项放入各自的键中
输入列表:
inputlist = ['example line begin','C40 D50','H4000 J30','; condition
1','E40 R50','G009 J56798','RFG50 F400','; condition 2','BG3400
F5600','C40 DH4000 J3F0','C40 D50','; condition 1','T40 R50','G009
J56798','RFG50 F400','condition3....]
预期的输出字典:
newDict = {'condition1':['E40 R50','G009 J56798','RFG50
F400'],'condition2':['BG3400 F5600','C40 DH4000 J3F0','C40 D50'],
'condition3':['........}
我还想存储尚未使用的初始部分。我不确定如何解决此问题,因为感觉我需要设置多个标志来切换开/关
这是我到目前为止所尝试的:
ozpattern = re.compile(r";\scondtion1")
outerpattern = re.compile(r";\scondition2")
ozFlag = False
outerFlag = False
for line in inputlist:
ozmatch = ozpattern.search(line)
outermatch = outerpattern.search(line)
if ozmatch:
ozFlag = True
ozKey = ''.join(ozmatch[2:].split(' '))
outerFlag = False
if ozFlag == True:
newDict[ozKey].append(line)
if outermatch:
outerKey = ''.join(outertempmatch[2:].split(' '))
ozFlag = False
outerFlag = True
continue
if outertempmatch:
newDict[outerKey].append(line)
但是我被困在这里,因为我需要在这里为几种不同的条件设置标志,这可能会很乏味。
答案 0 :(得分:0)
import re
inputlist = ['example line begin','C40 D50','H4000 J30','; condition 1','E40 R50','G009 J56798','RFG50 F400','; condition 2','BG3400 F5600','C40 DH4000 J3F0','C40 D50','; condition 3','T40 R50','G009J56798','RFG50 F400']
initialList = []
newDict = {}
key = ''
for i in inputlist:
m = re.match('; (.*)', i)
if m:
key = m.group(1)
elif key:
newDict.setdefault(key, []).append(i)
else:
initialList.append(i)
print(initialList)
print(newDict)
这将输出:
['example line begin', 'C40 D50', 'H4000 J30']
{'condition 1': ['E40 R50', 'G009 J56798', 'RFG50 F400'], 'condition 2': ['BG3400 F5600', 'C40 DH4000 J3F0', 'C40 D50'], 'condition 3': ['T40 R50', 'G009J56798', 'RFG50 F400']}