python - 查找字符串是否存在于 Python 的嵌套元组中

标签 python python-2.7

在 Python 2.7.x 中检查嵌套元组中是否存在字符串(或任何其他数据类型)的最佳(和最快)方法是什么?

例如:

RECIPES = (
    ('apple', 'sugar', 'extreme_Force'),
    ('banana', 'syrup', 'magical_ends'),
    ('caramel', 'chocolate', 'pancake_MONSTER'),
    ('banana',('someAnother','banana'))
)

如果 banana 出现在任何嵌套元组中并返回位置索引,则需要检查此元组,在本例中为 1,0

此外,元组可以嵌套到任意深度。

最佳答案

递归多位置索引:

import sys
from collections import Sequence,defaultdict

#making code python3-compatible
if sys.version_info[0] == 3:
    basestring = str

def buildLocator(tree):
    locator = defaultdict(list)
    def fillLocator(tree, locator,location):
        for index,item in enumerate(tree):            
            if isinstance(item,basestring):
                locator[item].append(location+(index,))
            elif isinstance(item,Sequence):
                fillLocator(item,locator, location+(index,))
    fillLocator(tree,locator,())
    return locator

RECIPES = (
    ('apple', 'sugar', 'extreme_Force'),
    ('banana', 'syrup', 'magical_ends'),
    ('caramel', 'chocolate', 'pancake_MONSTER'),
    ('banana',('someAnother','banana'))
)
locator = buildLocator(RECIPES)

print(locator['banana'])

打印

[(1, 0), (3, 0), (3, 1, 1)]

关于python - 查找字符串是否存在于 Python 的嵌套元组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12483330/

相关文章:

Python 2.7 : Pandas datetime does not work for future dates?

python - 创建一个类,用于存储字典并在 Python 3 中根据字典值更改设置对象属性

python - 属性错误 : 'list' object has no attribute 'endswith'

python - tkinter 条目和从右到左的光标

python - Python2.7中在带有空格和逗号的字符串后创建一个新行

python - Django/Python - 通过多对多关系中的公共(public)集对对象进行分组

python - conda 更新导致 ImportError : No module named tqdm

Python - 如何通过列表创建多个属性

python - 由于 python-magic 无法找到 libmagic,Python 上的 Pushbullet 会引发导入错误?

python - 自动导入给定文件夹中的所有 Python 文件?