在元组上分配字符串

时间:2013-11-04 21:34:05

标签: python string list recursion tuples

所以我试图在一个元组上分配一个字符串。 例如:

x = ["a", ("b", ("c", "d"))]

然后我想要

x = ["a", ("bc", "bd")]

最后:

x = ["abc", "abd"]  

然而,元组并不总是第二个元素: 例如:

x = [(("c", "d"), "b"), "a"]

简化为:

x = [("cb", "db"), "a"]

最后:

x = ["cba", "dba"]

我想知道如何编写单个函数来直接简化第一个表达式。

到目前为止我尝试的是:

def distribute(x):
    if isinstance(x, list) and any([True if isinstance(o, tuple) else False for o in x]):
        if isinstance(x[0], tuple):
            return (x[0][0] + x[1], x[0][1] + x[1])
        else:
            return (x[0] + x[1][0], x[0] + x[1][1])

print (distribute(["a", ("b", "c")]))

最终编辑: 编辑的奥斯卡代码适用于我的第二个例子:

def dist(tpl):
    if not isinstance(tpl[1], tuple) and not isinstance(tpl[0], tuple):
        return tpl
    if isinstance(tpl[1], tuple):
        ret = dist(tpl[1])
        return [tpl[0] + ret[0], tpl[0] + ret[1]]
    elif isinstance(tpl[0], tuple):
        ret = dist(tpl[0])
        return [ret[0] + tpl[1], ret[1] + tpl[1]]

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

尝试这个,它是一个递归解决方案,适用于问题中的两个示例,假设元组中的两个元素永远不会同时成为元组。

def dist(tpl):
    if not isinstance(tpl[0], tuple) and not isinstance(tpl[1], tuple):
        return tpl
    elif isinstance(tpl[0], tuple):
        ret = dist(tpl[0])
        return [ret[0] + tpl[1], ret[1] + tpl[1]]
    else:
        ret = dist(tpl[1])
        return [tpl[0] + ret[0], tpl[0] + ret[1]]

按预期工作:

dist(["a", ("b", ("c", "d"))])
=> ['abc', 'abd']

dist([(("c", "d"), "b"), "a"])
=> ['cba', 'dba']