Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
解包和重新打包元组(Python 2.x)_Python_Tuples - Fatal编程技术网

解包和重新打包元组(Python 2.x)

解包和重新打包元组(Python 2.x),python,tuples,Python,Tuples,我编写了一个函数,它接受、工作并返回简单的非嵌套元组 例如: 因为该逻辑仅适用于一维元组,但在概念上,每个嵌套级别都是相同的。我想知道是否有办法将嵌套元组(如((1,2,(3,),(4,))转换为普通的(1,2,3,4),然后将其转换回((1,2,(3,),(4,)) 基本上,我想要的是解包一个通用输入元组,使用它,然后将结果打包成与给定元组相同的形状 有没有一种类似蟒蛇的方法来完成这样的任务 也许解包可以用递归来解决,但是我不确定“重新打包”部分 这应该适用于重新包装: x = (1,(2,3

我编写了一个函数,它接受、工作并返回简单的非嵌套元组

例如:

因为该逻辑仅适用于一维元组,但在概念上,每个嵌套级别都是相同的。我想知道是否有办法将嵌套元组(如
((1,2,(3,),(4,)
)转换为普通的
(1,2,3,4)
,然后将其转换回
((1,2,(3,),(4,)

基本上,我想要的是解包一个通用输入元组,使用它,然后将结果打包成与给定元组相同的形状

有没有一种类似蟒蛇的方法来完成这样的任务


也许解包可以用递归来解决,但是我不确定“重新打包”部分

这应该适用于重新包装:

x = (1,(2,3),(4,(5,6)))
y = (9,8,7,6,5,4)

def map_shape(x, y, start=0):
    if type(x) == tuple:
        l = []
        for item in x:
            mapped, n_item = map_shape(item, y[start:])
            start += n_item
            l.append(mapped)
        return tuple(l), start
    else:
        return y[start], start+1

map_shape(x,y)[0]
输出:

(9, (8, 7), (6, (5, 4)))

拆包并不难:

def unpack(parent):
    for child in parent:
        if type(child) == tuple:
            yield from unpack(child)
        else:
            yield child
例如,你可以做这个把戏

重新包装有点棘手。我提出了以下建议,虽然有效,但恐怕不是很像蟒蛇:

def repack(structured, flat):
    output = []
    global flatlist
    flatlist = list(flat)
    for child in structured:
        if type(child) == tuple:
            output.append(repack(child, flatlist))
        else:
            output.append(flatlist.pop(0))

    return tuple(output)
示例用法是:

nested = ((1, 2, (3,)), (4,))
plain = tuple(unpack(nested))
renested = repack(nested, plain)

希望这有帮助

我提交我的版本。它使用相同的函数来展开和重构列表。如果
flat
None
它将变平,否则它将通过生成一个元组来重建

import collections


def restructure(original, flat=None):
    for el in original:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            if flat:
                yield tuple(restructure(el, flat))
            else:
                yield from restructure(el)
        else:
            yield next(flat) if flat else el


def gen():
    i = 0
    while True:
        yield i
        i += 1


def myfun(iterable):
    flat = tuple(restructure(iterable))
    # your transformation ..
    flat = gen()  # assigning infinite number generator for testing
    return restructure(iterable, flat=iter(flat))


x = (1, (2, 3), (4, (5, 6)))
print(tuple(y for y in myfun(x)))  # (0, (1, 2), (3, (4, 5)))

展平部分:。在重新打包方面,只需构造元组:
((t[0],t[1],(t[2],),(t[3],)
.ty,看起来平坦部分确实是递归的。但事实上,它不会保留元组原始结构的信息:/我也有类似的想法,希望能少一些“C-ish”tbh。但这确实是一个解决办法!真的!谢谢,我的荣幸。可能有一种方法可以在解包时记录该结构,然后重用该记录的结构重新打包,而无需递归。也许有一天会是一项有趣的运动,但现在是这里的就寝时间了。:-)是的,这只是一个保存递归级别的问题。。。也许我会对它多考虑一点,我认为它不仅仅是保存递归级别,因为给定示例中的1、2和4都具有相同的级别,但不属于一起。当然,除非你还将间歇的“跳跃”保存在中间。非常有趣的想法!但是10号线的产量是多少?从未见过在屈服后使用from。这是python 3.x吗?该死我忘了提到我正在使用2.xis有没有一种方法可以将“收益率从”转换为2.x等价物?是的,
yield from
是中引入的表达式,它将收益率委托给子生成器。你可以查一下。此外,扁平化部分取自评论部分的帖子,并且也是特定于版本的。
import collections


def restructure(original, flat=None):
    for el in original:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            if flat:
                yield tuple(restructure(el, flat))
            else:
                yield from restructure(el)
        else:
            yield next(flat) if flat else el


def gen():
    i = 0
    while True:
        yield i
        i += 1


def myfun(iterable):
    flat = tuple(restructure(iterable))
    # your transformation ..
    flat = gen()  # assigning infinite number generator for testing
    return restructure(iterable, flat=iter(flat))


x = (1, (2, 3), (4, (5, 6)))
print(tuple(y for y in myfun(x)))  # (0, (1, 2), (3, (4, 5)))