我在python中編寫了一個函數式代碼,我不明白爲什麼它返回一個None而不是代碼明確生成的正確值。在Python中的函數式編程:不返回正確的值
此腳本的目的是從CSV中獲取line.split(',')並重新組合從'{value1,value2,value3}'無意中拆分爲'value1,value2 ...'的所有值。值N」。
def reassemble(list_name):
def inner_iter(head, tail):
if head[0][0] == '{':
new_head = [head[0] + ',' + tail[0]]
if tail[0][-1] == '}':
return [new_head[0][1:-1]], tail[1:]
else:
inner_iter(new_head, tail[1:])
def outer_iter(corrected_list, head, tail):
if tail == []:
print corrected_list + head
return corrected_list + head
else:
if head[0][0] == '{':
head, tail = inner_iter(head, tail)
outer_iter(corrected_list + head, [tail[0]], tail[1:])
else:
outer_iter(corrected_list + head, [tail[0]], tail[1:])
return outer_iter([], [list_name[0]], list_name[1:])
下面是一個測試:
x = ['x','y', '{a', 'b}', 'c']
print reassemble(x)
這是奇怪的結果:
['x', 'y', 'a,b', 'c'] #from the print inside "outer_iter"
None #from the print reassemble(x)
注:我想保持代碼的功能作爲一個練習。
沒有運行代碼,我可以看到一些潛在的問題。你的inner和outer_iter函數並不總是返回一個值 – spicavigo 2013-04-25 12:11:18
這個問題是如何「過於本地化」的?我可以理解,我試圖將這篇文章與Python對函數式編程的解釋分開,可能被誤解或可能違反Stackoverflow策略(這是有爭議的),但這個問題仍然非常相關 - 請參閱Elazar的文章評論。 – TimY 2013-04-25 22:34:47
這個問題絕對不是「過於本地化」。 – Elazar 2013-04-27 17:05:54