一个更快的嵌套元组列表和返回

时间:2013-03-15 14:02:48

标签: python performance list nested tuples

我正在尝试执行元组列表并列出在未知深度和形状的嵌套序列上的元组转换。这些电话正在进行数十万次,这就是为什么我要尽可能多地挤出速度。

非常感谢任何帮助。

这是我到目前为止所拥有的......

def listify(self, seq, was, toBe):
  temp = []
  a = temp.append
  for g in seq:
    if type(g) == was:
      a(self.listify(g, was, toBe))
    else:
      a(g)
  return toBe(temp)

要求列表的元组看起来像这样:

self.listify((...), tuple, list)

编辑:是的,我完全错过了枚举(来自旧的实现)并忘记输入else部分。

感谢你们两位的帮助。我可能会选择协同程序。

3 个答案:

答案 0 :(得分:6)

我最近和coroutines一起工作很安静。优点是可以减少方法调用的开销。将新值发送到协程比调用函数更快。虽然你不能制作一个递归协程,它会抛出一个ValueError: generator already executing,但是你可以建立一个协同工作池 - 你需要一个工作者为树的每个级别。我已经制作了一些可行的测试代码,但尚未查看时序问题。

def coroutine(func):
    """ A helper function decorator from Beazley"""
    def start(*args, **kwargs):
        g = func(*args, **kwargs)
        g.next()
        return g
    return start

@coroutine
def cotuple2list():
    """This does the work"""
    result = None
    while True:
        (tup, co_pool) = (yield result)
        result = list(tup)
        # I don't like using append. So I am changing the data in place.
        for (i,x) in enumerate(result):
            # consider using "if hasattr(x,'__iter__')"
            if isinstance(x,tuple):
                result[i] = co_pool[0].send((x, co_pool[1:]))


@coroutine
def colist2tuple():
    """This does the work"""
    result = None
    while True:
        (lst, co_pool) = (yield result)
        # I don't like using append so I am changing the data in place...
        for (i,x) in enumerate(lst):
            # consider using "if hasattr(x,'__iter__')"
            if isinstance(x,list):
                lst[i] = co_pool[0].send((x, co_pool[1:]))
        result = tuple(lst)

来自HYRY帖子的纯蟒蛇替代品:

def list2tuple(a):
    return tuple((list2tuple(x) if isinstance(x, list) else x for x in a))
def tuple2list(a):
    return list((tuple2list(x) if isinstance(x, tuple) else x for x in a))

建立一个协程池 - 这是一个池的黑客,但它的工作原理:

# Make Coroutine Pools
colist2tuple_pool = [colist2tuple() for i in xrange(20) ]
cotuple2list_pool = [cotuple2list() for i in xrange(20) ]

现在做一些时间 - 比较:

def make_test(m, n):
    # Test data function taken from HYRY's post!
    return [[range(m), make_test(m, n-1)] for i in range(n)]
import timeit
t = make_test(20, 8)
%timeit list2tuple(t)
%timeit colist2tuple_pool[0].send((t, colist2tuple_pool[1:]))

结果 - 注意第二行's'旁边的'u': - )

1 loops, best of 3: 1.32 s per loop
1 loops, best of 3: 4.05 us per loop

真的太快了,无法相信。有人知道timeit是否与协同程序一起使用? 这是老式的方式:

tic = time.time()
t1 = colist2tuple_pool[0].send((t, colist2tuple_pool[1:]))
toc = time.time()
print toc - tic

结果:

0.000446081161499

较新版本的Ipython和%timit会发出警告:

  

最慢的跑步比最快跑的时间长9.04倍。这可以是   意味着中间结果被缓存1000000循环,最好   每个循环3:317 ns

经过一些进一步的调查,python生成器不是魔术,发送仍然是一个函数调用。我的基于生成器的方法看起来更快的原因是我在列表上进行了一个就地操作 - 这导致更少的函数调用。

我在最近的talk中写了很多其他详细信息。

希望这可以帮助那些希望玩发电机的人。

答案 1 :(得分:3)

分别定义两个功能:

def list2tuple(a):
    return tuple((list2tuple(x) if isinstance(x, list) else x for x in a))

def tuple2list(a):
    return list((tuple2list(x) if isinstance(x, tuple) else x for x in a))

一些测试:

t = [1, 2, [3, 4], [5, [7, 8]], 9]
t2 = list2tuple(t)
t3 = tuple2list(t2)
print t2
print t3

结果:

(1, 2, (3, 4), (5, (7, 8)), 9)
[1, 2, [3, 4], [5, [7, 8]], 9]

编辑以获取快速版本:

def list2tuple2(a, tuple=tuple, type=type, list=list):
    return tuple([list2tuple2(x) if type(x)==list else x for x in a])

def tuple2list2(a, tuple=tuple, type=type):
    return [tuple2list2(x) if type(x)==tuple else x for x in a]

比较我还包括cython版本:

%%cython

def list2tuple3(a):
    return tuple([list2tuple3(x) if type(x)==list else x for x in a])

def tuple2list3(a):
    return [tuple2list3(x) if type(x)==tuple else x for x in a]

创建一些嵌套列表:

def make_test(m, n):
    return [[range(m), make_test(m, n-1)] for i in range(n)]

t = make_test(20, 8)
t2 = list2tuple2(t)

然后比较速度:

%timeit listify(t, list, tuple)
%timeit listify(t2, tuple, list)
%timeit list2tuple(t)
%timeit tuple2list(t2)
%timeit list2tuple2(t)
%timeit tuple2list2(t2)
%timeit list2tuple3(t)
%timeit tuple2list3(t2)

结果是:

listify
1 loops, best of 3: 828 ms per loop
1 loops, best of 3: 912 ms per loop

list2tuple generator expression version
1 loops, best of 3: 1.49 s per loop
1 loops, best of 3: 1.67 s per loop

list2tuple2 list comprehension with local cache
1 loops, best of 3: 623 ms per loop
1 loops, best of 3: 566 ms per loop

list2tuple3 cython
1 loops, best of 3: 212 ms per loop
10 loops, best of 3: 232 ms per loop

答案 2 :(得分:0)

由于上面的答案不涉及字典值中的元组或列表,我发布了自己的代码:

def tuple2list(data):
    if isinstance(data, dict):
        return {
            key: tuple2list(value)
            for key, value in data.items()
        }
    elif isinstance(data, (list, tuple)):
        return [
            tuple2list(item)
            for item in data
        ]
    return data

def list2tuple(data):
    if isinstance(data, dict):
        return {
            key: list2tuple(value)
            for key, value in data.items()
        }
    elif isinstance(data, (list, tuple)):
        return tuple(
            list2tuple(item)
            for item in data
        )
    return data
相关问题