在多维列表中搜索元素并返回子列表号?

时间:2016-04-28 19:00:58

标签: python python-2.7

以前我有一个关于查找元素是否存在于嵌套列表中的问题,并在下面的链接中得到了响应。

Search of Element inside a multi-dimensional List Not Working. Any Clue

想知道函数是否也可以发出一个值,该值表示该元素存在于哪个子列表中?下面的代码说明元素是否退出:

def in_nested_list(item, x):
    if not isinstance(x, list):
        return x == item
    else:
        return any(in_nested_list(item, ix) for ix in x)

list1 = []
list1.append([['red'], ['blue'], ['bla']])

print list1

list1.append([['hello'], ['blue'], ['bla']])
print list1

if in_nested_list('hello', list1):
    print "Found Hello"
else:
    print "Not Found Hello"

我想知道如何更改该功能,以便说明该元素退出哪个子列表,以便我可以根据特定的子列表追加更多数据。

一个。从上面的例子中,if条件将打印出Hello。但是,如果它也返回或保存一个输出变量,如上面的情况中sublist_no,即子列表1,那么我可以附加更多的变量。

例如:现在输出返回TRUE,子列表号也返回1,这样我可以在调用函数后执行以下过程。

list1[sublist_no].append(['Bug'])

假如我搜索红色元素,输出将为TRUE,sublist_no为0,这样我就可以将更多变量附加到第一个列表。 list1[sublist_no].append('[Rasberry]') # i.e. onto the first sub-list.

以上查询的任何线索?请注意你的评论...

2 个答案:

答案 0 :(得分:0)

由于您的原始函数可以处理比列表列表更复杂的嵌套结构,因此嵌套的“index”函数也应如此:

def in_nested_list(item, x):
    if item == x:
        return []
    if isinstance(x, list):
        for i, ix in enumerate(x):
            r = in_nested_list(item, ix)
            if r != -1:
                return [i] + r  # highest level index plus path in sublist
    return -1  # not found in any (nested) sublist

# if not found at all: return -1
# if item == x: return []
# else: return [a, b, c] such that item == x[a][b][c]

> in_nested_list(3, [[1, 2], [3, 4]])
[1, 0]

> in_nested_list(3, [[1, 2], [[5, 3], 4]])
[1, 0, 1]

> in_nested_list(3, 3)
[]

> in_nested_list(3, [1, 2])
# -1

这允许您在您选择的任何嵌套级别附加内容。至于你的问题,简单结构中子列表的索引是in_nested_list(...)[0](如果存在,否则会引发错误)。

答案 1 :(得分:0)

我利用杠杆来修改你的功能。

def in_nested(item, container):
    if not isinstance(container, list):
        raise TypeError
    for elem in container:
        if isinstance(elem, list):
            found = in_nested(item, elem)
            if not found:
                pass
            elif isinstance(found, bool):
                # Item is present in this list
                return elem
                # List containing item is present in this container
                # Comment above return to use it.
                return container
            else:
                # Return the deepest list and not the most outer list containing it.
                return found
        else:
            return item == elem


_input = [[['red'], ['blue'], ['bla']], [['hello'], ['blue'], ['bla']]]
out = in_nested('hello', _input)
if out:
    print "Found Hello", out
else:
    print "Not Found Hello"

out.append('new')
print 'Added new to original input', _input

out = in_nested('Hello', _input)  # hello with capital H
if out:
    print "Found Hello", out
else:
    print "Not Found Hello"

# Prints:
# Found Hello ['hello']
# Added new to original input [[['red'], ['blue'], ['bla']], [['hello', 'new'], ['blue'], ['bla']]]
# Not Found Hello

注意:如果项目存在,它会为您提供目标列表本身无。您不必再次找到该列表。只需追加结果即可。

相关问题