返回列表

时间:2016-09-18 01:10:01

标签: list python-3.x recursion nested sublist

给定一个包含许多可能的子列表的列表,这些子列表嵌套到任意深度并具有可变数量的元素,是否有办法返回满足特定条件的所有子列表的所有实例的索引? / p>

例如:

list1 = [1, 4, 7, ["a", "h", "b"], 2]
list2 = [1, 4, 7, "x", "g", ["a", 5, 8, "p", "b"], 2, 4, 7, "k", 9]
list3 = [1, 4, 7, ["a", "z", ["a", 6, "b"], "b"], 5, 3]
list4 = [1, 4, 7, ["a", "b", "c"], 3, 4]

sublist_function(list1, {[0]:'a', [-1]: 'b'}) 
# should return [[3]] (One instance of a matching sub-list (whose 0th element is 'a' and whose last element is 'b') found at list1[3])
sublist_function(list2, {[0]:'a', [-1]: 'b'}) 
# should return [[5]] (One instance of a matching sub-list, found at list2[5])
sublist_function(list3, {[0]:'a', [-1]: 'b'}) 
# should return [[3], [3][2]] (Two instances of a matching sub-list, found at list3[3] and list3[3][2])
sublist_function(list4, {[0]:'a', [-1]: 'b'}) 
# should return [] (There are no instances of a matching sub-list in list4)

我认为将一个函数的代码调整为可以返回子列表的索引的子代码的存在/不存在是一个简单的问题,但这证明了像我这样的初学程序员是一个很大的挑战。原始函数的代码可以在我对@AdamSmith的先前问题的回答中找到,Find generic sub-lists within a list

更新:使用How to find the number of nested lists in a list?作为指导,以下是迄今为止我能够提出的最好的,但1)它只返回每个匹配子列表的LAST索引,2)替换匹配子列表的最后一个索引,其中包含第一个出现的相同子列表的最后一个索引。我甚至不担心它没有一个参数来指定列表的哪些特征要匹配,而是在函数本身中定义它 - 这点就是锦上添花:

def sublist_function(lst, ind=None):
    if ind is None:
        ind = []
    for el in lst:
        if isinstance(el, list) and el[0] == 'a' and el[-1] == 'b':
            ind.append([lst.index(el)])
            sublist_function(el, ind)
        elif isinstance(el, list):
            sublist_function(el, ind)
    return ind

list3 = [1, 4, 7, ["a", "z", ["a", 6, "b"], "b"], 5, 3]
print(sublist_function(list3)) #should return '[[3], [3][2]]'
>> [[3], [2]]

list5 = [1, 4, ["a", 5, "b"], 3, 4, 6, ["a", 5, "b"], 5]
print(sublist_function(list5)) #identical sub-lists (should return [[2], [6]])
>> [[2], [2]]

list6 = [1, 4, ["a", 7, "b"], 3, 4, 6, ["a", 5, "b"], 5]
print(sublist_function(list6)) #unique sub-lists (correctly returns [[2], [6]])
>> [[2], [6]]

0 个答案:

没有答案