如何检查一个元素是否在嵌套列表中?

4

如何检查一个元素是否在嵌套列表中?

我正在尝试定义一个函数nested(x, ys),用于测试一个值x是否出现在整数嵌套列表ys中。结果必须为TrueFalse


3
我们能看到你的努力吗? - squiguy
2
ys是已知深度(即2D数组)还是可变深度(即树)? - Hugh Bothwell
def nested(x, ys): if type(ys[0]) == type([]): return (nested(x, ys[0]) or nested(x, ys[1:])) else: if x == ys[0]: return True else: return False - Fatmir Alijaj
这是我到目前为止的努力... - Fatmir Alijaj
例如,ys = [[2,1,],3] - Fatmir Alijaj
2个回答

7

循环遍历嵌套的列表并对其进行测试;any()函数可以使此过程更加高效:

def nested(x, ys):
    return any(x in nested for nested in ys)

假设ys只嵌套了一层。

如果需要递归,您可以使用以下方法:

def flatten(lst):
    for elem in lst:
        if isinstance(elem, (list, tuple)):
            for nested in flatten(elem):
                yield nested
        else:
            yield elem

def nested(x, ys):
    return any(x == nested for nested in flatten(ys))

我使用了一个简化的测试,只针对listtuple,以避免对字符串进行“展开”操作。


那么我理解标准库中没有递归嵌套检查了? - BlackVegetable
没有这样的函数;我认为,任意嵌套的列表并不那么统一,无法适应标准函数。 - Martijn Pieters
谢谢你,Martij Pieters! - Fatmir Alijaj

2
这适用于任何深度级别:
import collections

def nested(x, ys):
    if x in ys: return True        

    # only keep iterables
    nests = [y for y in ys if isinstance(y, collections.Iterable)]

    # call nested() on each iterable
    return any(nested(x, nest) for nest in nests)

# returns True, will go into multiple nests to find 5
print nested(5, [[1,2],[3,4],[1,2,[3,5]]])

谢谢bcorso。但这对我来说太高级了。当然它有效。谢谢。 - Fatmir Alijaj
如何将嵌套函数作为递归使用以解决问题? - Fatmir Alijaj
这确实使用了递归。对于所有嵌套在nests中的nest,any(nested(x, nest) for nest in nests)会递归调用nested函数来处理可迭代元素。 - bcorso
非常感谢您的帮助和时间。 - Fatmir Alijaj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接