我有一個儲存與縮進/空格中源會計師樹解析層次:如何基於與蟒蛇縮進
Income
Revenue
IAP
Ads
Other-Income
Expenses
Developers
In-house
Contractors
Advertising
Other Expenses
有水平的固定號碼,所以我想扁平化層次結構,通過使用3個字段(實際數據具有6個級別,簡化例如):
for rownum in range(6,ws.max_row+1):
accountName = str(ws.cell(row=rownum,column=1).value)
indent = len(accountName) - len(accountName.lstrip(' '))
if indent == 0:
l1 = accountName
l2 = ''
l3 = ''
elif indent == 3:
l2 = accountName
l3 = ''
else:
l3 = accountName
w.writerow([l1,l2,l3])
:
L1 L2 L3
Income
Income Revenue
Income Revenue IAP
Income Revenue Ads
Income Other-Income
Expenses Developers In-house
... etc
我可以通過檢查之前的帳戶名的空格數要這樣做
有沒有一種更靈活的方式來實現這一點,基於當前行的縮進與前一行相比,而不是假設它每個級別總是3個空格? L1
將始終沒有縮進,並且我們可以相信較低的級別會比其父級進一步縮進,但每個級別可能不總是3個空格。
更新,最終以此作爲邏輯的肉,因爲我最終希望擁有內容的帳戶列表,似乎最簡單的方法是使用縮進來決定是重置,追加還是彈出列表:
if indent == 0:
accountList = []
accountList.append((indent,accountName))
elif indent > prev_indent:
accountList.append((indent,accountName))
elif indent <= prev_indent:
max_indent = int(max(accountList,key=itemgetter(0))[0])
while max_indent >= indent:
accountList.pop()
max_indent = int(max(accountList,key=itemgetter(0))[0])
accountList.append((indent,accountName))
所以在輸出的每一行accountList都是完整的。
感謝這個,我最終希望能夠輸出在與行的內容沿每一行的層次,所以我稍作修改,但這讓我朝着正確的方向前進。 –