递归搜索嵌套元组

2024-09-30 14:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些数据看起来像

data = [('h'), (('j','kjjy')), ((('khg','hello')))]

我希望能够递归搜索“hello”并只返回true或false,但我不知道如何做


Tags: 数据falsetruehellodatakjjykhg
3条回答

以下是一个例子:

import numpy as np

array = np.asarray(a)

def searchForWord(array, word):

    #base case
    if (array.size == 0) return false

    #recursive case
    if word in array[0] return true


    array = np.delete(array, 0)
    searchForWord(array, word)



您可能会遇到问题,因为numpy数组将是元组数组。只要让我知道它是否有效

您可以递归地执行此操作:

def find(text, data):
    # loop over all items (tuples or strings)
    for item in data:
        # if it's a tuple, recurse
        if isinstance(item, tuple): 
            if find(text, item): 
                return True 
        # if it's a string and a match return true
        if item==text: 
            return True 
    return False 
a=[('h'), (('j','kjjy')), ((('khg','hello')))]

for x in range(len(a)):
    tup = a[x]
    print(tup)
    print('hello' in tup)

输出:

h
False
('j', 'kjjy')
False
('khg', 'hello')
True

相关问题 更多 >