在 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/