Python 请解释一下这个代码的工作原理?

Python 请解释一下这个代码的工作原理?,python,Python,我是python的初学者。我不明白,事实上,最终的回报并没有以: def gSubsets(L): if len(L) == 0: print '2' return [[]] smaller = gSubsets(L[:-1]) extra = L[-1:] print L new = [] for small in smaller: new.append(small+extra)

我是python的初学者。我不明白,事实上,最终的回报并没有以:

def gSubsets(L):
    if len(L) == 0:
        print '2'
        return [[]]
    smaller = gSubsets(L[:-1]) 
    extra = L[-1:]
    print L     
    new = []
    for small in smaller:
        new.append(small+extra)
    return smaller+new
print gSubsets([1,2])

把它拆成碎片

smaller + new =[[][5]]
这个输出

def gSubsets(L): #recursive function
    if len(L) == 0: #when weve reached the last subset we then have to handle an empty list
        print '2'
        return [[]] #returns a list of lists for the small in smaller
    smaller = gSubsets(L[:-1]) #get subsets by recursive call for all elements in the list except the last one
    extra = L[-1:] #get the last element in the list not used in this recursive call
    print L     
    new = []
    for small in smaller: #loop through list of lists from recursive call
        new.append(small+extra) #append all combinations of the last element in the list to every other element in the same list to new
    return smaller+new #return subset with new combinations

print gSubsets([1,2])
顺便说一句,在python中,变量和函数名应该使用下划线,这是首选语法,我也会处理变量名。。你希望他们非常具体,以便任何其他路过的人都能马上明白。。这就是我重命名变量的方式

>>> 2
>>> [1]
>>> [1, 2]
>>> [[], [1], [2], [1, 2]]

帮助我们,帮助你。代码打算做什么?它在做什么?我的建议是:创建一个新问题,包括更好的解释它会返回什么?要理解代码的功能,拿出一张纸,写下所有变量的值。然后一行一行地遍历代码,添加新值。这实际上是在生成列表的子集。您应该一步一步地进行。此函数递归调用自身以创建附加到新列表中的子集感谢您消除了我的疑虑。@bp_28当然,这有助于您理解它的工作原理吗?另请参阅我的最新编辑,并对您的对象/变量名称提出一些建议
def generate_subsets_from_list(input_list):
    if len(input_list) == 0:
        # print '2'  -- not sure why you are printing 2 here?
        return [[]]
    subsets = generate_subsets_from_list(input_list[:-1]) 
    last_element = L[-1:]
    print L     
    return_list = []
    for subset in subsets:
        return_list.append(subset+last_element)
    return subsets+return_list

initial_list = [1,2]
print generate_subsets_from_list(initial_list)