嗯...这是一个可能的答案。我想做一些小事情,比如从列表的第一行中删除字段名称。还要使用列名来寻址字段,以便调用代码更易于阅读(例如 theList['Name'][1])。这个答案现在很好。我想不出一种简单的方法来准确计算列名,因为它们可能包含空格。调用者必须将其传入。
def getFldPositions( cliData, fldList ):
pos = [ ]
for curItem in fldList:
pos.append( data.find(curItem))
pos.append( pos[-1] + len(fldList[-1] ))
return pos
def getCLIAsList( cliData, fldList ):
pos = getPositions( cliData, fldList )
newList = []
for line in cliData.splitlines():
newDict = [ ]
for i, fld in enumerate(fldList):
newDict.append( line[pos[i]:pos[i+1]].strip( ))
newList.append(newDict)
return newList
def getCLIAsDict( cliData ):
pos = getPositions( cliData, fldList )
newList = []
for line in cliData.splitlines():
newDict = { }
for i, fld in enumerate(fldList):
newDict.update([ ( fld, line[pos[i]:pos[i+1]].strip() ) ])
newList.append(newDict)
return newList
fldList = ['Client ID', 'Name', 'Value 1', 'Value 2']
data = 'Client ID Name Value 1 Value 2\n' \
'5 Joe last 5 1 5 2\n' \
'6 Frank Last 6 1 6 2\n'
theList = getCLIAsList( data, fldList )
# theList = getCLIAsDict( data, fldList )
print( theList )
print( 'ID: ' + theList[1][0] )
它返回这个:
[['Client ID', 'Name', 'Value 1', 'Value 2'], ['5', 'Joe last', '5 1', '5 2'], ['6', 'Frank Last', '6 1', '6 2']]
ID: 6