首页 > 解决方案 > 在 Python 的嵌套数组中搜索字符串中的字符串

问题描述

我正在尝试使用一个基本函数来在嵌套列表中的另一个字符串中查找一个字符串。但它无法找到相同的。有什么根本错误吗?

import Tkinter, Tkconstants, tkFileDialog
from   Tkinter import *
import subprocess
import ttk
import re

def find_index_sub_string(needle,haystack):
    return [i for i, x in enumerate(haystack) if needle in x]

mc_pool = [['fruit,apple', '1,appl_c', [''], '1,am', '1,as', ['fruit,apple,am-fruit,apple,as-rocky,1'], '/abc/bb/ccc/dd/e', ['1,aa', ['fruit,apple,aa', 'aa', 1, [], [], [], [], [], []]]], ['apple,appl_c', '', [''], '1,mm', '1,ms', ['apple,appl_c,mm-apple,appl_c,ms-rambo,1'], '/aa/bbbd/cc/dddd', ['']]]
mc_pool_cln = [['fruit,apple', '1,appl', ['fruit,apple,mas', 'mas', '5'], '1,am', '1,as', ['fruit,apple,am-fruit,apple,as-rocky,1'], '/abc/bb/ccc/dd/e', ['1,aa', ['fruit,apple,aa', 'aa', 1, [], [], [], [], [], []]]], ['apple,appl', '', [''], '1,mm', '1,ms', ['apple,appl,mm-apple,appl,ms-rambo,1'], '/aa/bbbd/cc/dddd', ['']]]

mc_idx = find_index_sub_string('_c', mc_pool)
print mc_idx 

mc_idx = find_index_sub_string('_c', mc_pool_cln)
print mc_idx 

更新:

  1. 添加了另一个不包含任何字符串的数组 mc_pool_cn,即_c..
  2. 期待输出之类的,[[0,1], [1,0], [1,5]]..即出现的子字符串的相应索引位置..

标签: pythonpython-2.7

解决方案


您正在搜索完全匹配,而不是子字符串。

而且由于您有递归嵌套列表,因此您需要使用递归函数来搜索任何深度。

def match_substring_recursive(needle, haystack):
    if isinstance(haystack, str):
        return needle in haystack
    else:
        return any(match_substring_recursive(needle, x) for x in haystack)

def find_index_sub_string(needle, haystack):
    return [i for i, x in enumerate(haystack) if match_substring_recursive(needle, x)]

推荐阅读