python - 在 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
更新:
- 添加了另一个不包含任何字符串的数组 mc_pool_cn,即
_c
.. - 期待输出之类的,
[[0,1], [1,0], [1,5]]..
即出现的子字符串的相应索引位置..
解决方案
您正在搜索完全匹配,而不是子字符串。
而且由于您有递归嵌套列表,因此您需要使用递归函数来搜索任何深度。
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)]
推荐阅读
- apache - 当存在同名文件时,Htaccess 正在匹配目录
- excel - Vlookup 并求和一个包含逗号分隔值的单元格
- vb.net - 如何使用 DataGridView.AutoGenerateColumns = False 创建我自己的列
- python - Perforce - 创建和编辑更改列表
- python - 如何在不修改原始字符串的情况下将 .islower() 用于 if 语句
- sql - SQL - 如何对来自 3 个其他查询的列求和
- css - Bootstrap 工具提示箭头边框和背景颜色
- android - 如何为嵌套类函数编写 Frida 钩子?
- python - 如何在 pyspark 中调用预测函数?
- java - 为什么 FileWriter 没有像它应该的那样创建一个新行?JAVA