查找Python中嵌套元组中是否存在字符串

Nan*_*ali 4 python python-2.7

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

例如:

RECIPES = (
    ('apple', 'sugar', 'extreme_Force'),
    ('banana', 'syrup', 'magical_ends'),
    ('caramel', 'chocolate', 'pancake_MONSTER'),
    ('banana',('someAnother','banana'))
)
Run Code Online (Sandbox Code Playgroud)

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

此外,元组可以嵌套到任何深度.

Odo*_*ois 7

递归多位置索引:

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'])
Run Code Online (Sandbox Code Playgroud)

版画

[(1, 0), (3, 0), (3, 1, 1)]
Run Code Online (Sandbox Code Playgroud)

  • 更好地使用`basestring`,因为它被标记为python2.7 (3认同)