用于在python中拆分列表的递归函数

时间:2017-10-09 12:01:10

标签: python recursion

我有一个我编写的函数来获取任意值列表并将其以特定值分割为子列表。基本上,我想获取一个列表并在特定值的所有出现时将其拆分,返回一个子列表列表。我认为最简单的方法是通过下面的递归函数。

def recsplit(L, val):
    if L.count(val)==0: # If there are no occurrences, return the whole list
        return L
    elif L.index(val)==0: # If the value is the first element, return everything else
        return recsplit(L[1:],val)
    else: # Otherwise, split at the first instance of value
        return L[:L.index(val)], recsplit(L[L.index(val)+1:],val)

功能的功能如下:

>>> P = [1,2,3,4,5,None,None,6,7,8,None,9,10,11,None]
>>> recsplit(P,None) 
[[1,2,3,4,5],[6,7,8],[9,10,11]]

不幸的是我得到以下输出:

([1, 2, 3, 4, 5, 6, 7], ([8, 9, 10, 11], ([12, 13, 14, 15], [])))

我确信有办法解决这个问题,但我已经尝试了很多我能想到的组合,但似乎没有一个对我有效。

2 个答案:

答案 0 :(得分:2)

当你可以使用itertools.groupby时,我不认为递归是最简单的方法:

  var t = $("#datatable").DataTable({
        "order": [[ 1, 'asc' ]],
        "ajax": "questions1/get-data",
        "deferRender": true,
        "processing": true,
        sAjaxDataProp: "",
        "columns": [
            { "data": "id" },
            { "data": "name" },
            { "data": "description" },
            { "data": "answers.[, ].name" },
            { "data": "campaigns.[, ].name" },
            { "data": "label" },
            {
                sortable: false,
                "render": function ( data, type, full, meta ) {
                    var buttonID = full.id;
                    return '@can('view', $question)<a href="{{ url('/admin/survey-details/questions/' + buttonID ) }}" class="btn btn-success btn-xs" title="View Question"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"/></a>@endcan
                        @can('update', $question)<a href="{{ url('/admin/survey-details/questions/12/edit') }}" class="btn btn-primary btn-xs" title="Edit Question"><span class="glyphicon glyphicon-pencil" aria-hidden="true"/></a>@endcan';
                }
            }

        ],

    });

还要记住,递归并不便宜

答案 1 :(得分:1)

正如有人已经指出的那样,递归函数可能不是这个特定任务的最佳方法(至少在python中)。但是既然你问过,这里是带有递归调用的代码,可以生成你期望的确切输出。

def recsplit(L, val, out=[[]]):
    if L == []:
        return out
    elif L[0] == val and out[-1] != [] and L[1:].count(val) != len(L[1:]):
        return recsplit(L[1:], val, out + [[]])
    elif L[0] != val and L[0] is not None:
        return recsplit(L[1:], val, out[:-1] + [out[-1] + [L[0]]])
    else:
        return recsplit(L[1:], val, out)

P = [1,2,3,4,5,None,None,6,7,8,None,9,10,11,None]
P1 = [1,2,None,3,4,5,None,"x","x",None,6,7,8,"x",9,10,11,None,"x","x"]  
print("Subs of P by None =", recsplit(P,None))
print("Subs of P1 by x =", recsplit(P1,"x"))
print("Subs of P1 by None =", recsplit(P1,None))

==&GT;

Subs of P by None = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10, 11]]
Subs of P1 by x = [[1, 2, 3, 4, 5], [6, 7, 8], [9, 10, 11]]
Subs of P1 by None = [[1, 2], [3, 4, 5], ['x', 'x'], [6, 7, 8, 'x', 9, 10, 11], ['x', 'x']]