我有一個(gè)函數(shù),它使用嵌套循環(huán)處理一些非常嵌套的數(shù)據(jù)。其簡(jiǎn)化結(jié)構(gòu)如下:
def process_elements(root):
for a in root.elements:
if a.some_condition:
continue
for b in a.elements:
if b.some_condition:
continue
for c in b.elements:
if c.some_condition:
continue
for d in c.elements:
if d.some_condition:
do_something_using_all(a, b, c, d)
這在我看來(lái)不太pythonic,所以我想重構(gòu)它。我的想法是將其分解為多個(gè)功能,比如:
def process_elements(root):
for a in root.elements:
if a.some_condition:
continue
process_a_elements(a)
def process_a_elements(a):
for b in a.elements:
if b.some_condition:
continue
process_b_elements(b)
def process_b_elements(b):
for c in b.elements:
if c.some_condition:
continue
process_c_elements(c)
def proccess_c_elements(c):
for d in c.elements:
if d.some_condition:
do_something_using_all(a, b, c, d) # Problem: I do not have a nor b!
如您所見(jiàn),對(duì)于更嵌套的級(jí)別,我需要使用其所有“父”元素來(lái)執(zhí)行某些操作。這些函數(shù)將具有唯一的作用域,因此我無(wú)法訪(fǎng)問(wèn)這些元素。將所有前面的元素傳遞給每個(gè)函數(shù)(比如proccess_c_elements(c, a, b)
)確實(shí)看起來(lái)很難看,而且對(duì)我來(lái)說(shuō)也不是很pythonic。。。
Any ideas?
FWIW,我找到了一個(gè)解決方案,它將所有處理封裝在一個(gè)類(lèi)中,并具有跟蹤當(dāng)前處理的元素的屬性: