Python深拉链 [英] Python deep zip

查看:105
本文介绍了Python深拉链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个像zip一样的函数。我不善于解释我的意思,所以我只会显示我想要做的事情的'代码'。

  a = [1,2,3,[4,5]] 
b = a [:]
zip(a,b)== [(1,1),(2,2), (3,3),([4,5],[4,5])]
myzip(a,b)== [(1,1),(2,2),(3,3) ,[(4,4),(5,5)]]

它甚至不好笑。我试图用递归lambdas以简单的函数式编写它,以使我的代码更漂亮。我想要这样的myzip,因为我想用我的另一个函数使用它的输出,它将函数映射到树上。 (func,tree):
return map(lambda x:func(x)if is not isinstance(x,list)else tree_map(func,x),
tree)

我一直试图用zip来做类似的事情,但我似乎无法把头围住它。有没有人有任何想法,我怎么可以写myzip?



编辑:看看tree_map!是不是很漂亮!至少我这么认为,但我的母语是Scheme:P
,并且我希望myzip能够尽可能深入。基本上,我希望myzip保留通过它的树的结构。此外,myzip只能处理形状相同的树。

解决方案

我认为以下内容应该可以工作:

 导入集合

def myzip(* args):
如果全部(isinstance(arg,collections.Iterable )for arg in args):
return [myzip(* vals)for vals in zip(* args)]
return args

结果:

 >>> a = [1,2,3,[4,[5,6]]] 
>>> b = [1,2,3,[4,[5,6]]]
>>> myzip(a,b)
[(1,1),(2,2),(3,3),[(4,4),[(5,5),(6,6)]] ]

请注意,我使用 collections.Iterable 而不是 list 在类型检查中,以便行为更像是使用元组和其他迭代器的 zip()


I am trying to write a function like zip. I am not good at explaining what I mean, so i will just show 'code' of what i'm trying to do.

a = [1,2,3,[4,5]]
b = a[:]
zip(a, b) == [(1,1), (2,2), (3,3), ([4,5],[4,5])]
myzip(a, b) == [(1,1), (2,2), (3,3), [(4,4), (5,5)]]

I am so stuck on this it's not even funny. I am trying to write it in a simple functional way with recursive lambdas, to make my code prettier. I want myzip like this because i want to use its output with another function I wrote which maps a function to a tree

def tree_map(func, tree):
    return map(lambda x: func(x) if not isinstance(x, list) else tree_map(func, x), 
               tree)

I have been trying to do something similar to this with zip, but I can't seem to wrap my head around it. Does anyone have any ideas on how i could write myzip?

Edit: Look at tree_map! isn't that pretty! i think so at least, but my mother tongue is Scheme :P and also, I want myzip to go as deep as it needs to. basically, I want myzip to retain the structure of the trees i pass it. Also, myzip will only handle trees that are the same shape.

解决方案

I think the following should work:

import collections

def myzip(*args):
    if all(isinstance(arg, collections.Iterable) for arg in args):
        return [myzip(*vals) for vals in zip(*args)]
    return args

Result:

>>> a = [1,2,3,[4,[5,6]]]
>>> b = [1,2,3,[4,[5,6]]]
>>> myzip(a, b)
[(1, 1), (2, 2), (3, 3), [(4, 4), [(5, 5), (6, 6)]]]

Note that I use collections.Iterable instead of list in the type checking so that the behavior is more like zip() with tuples and other iterables.

这篇关于Python深拉链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆