3

深さと形状が不明なネストされたシーケンスで、タプルからリストへの変換とリストからタプルへの変換を実行しようとしています。何十万回も電話がかかってきているので、できるだけスピードを出そうとしています。

どんな助けでも大歓迎です。

これが私がこれまでに持っているものです...

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部分を入力するのを忘れました。

お二人のご協力ありがとうございます。私はおそらくコルーチンに行きます。

4

3 に答える 3

6

私は最近、静かなコルーチンで作業しています。利点は、メソッド呼び出しのオーバーヘッドを減らすことです。コルーチンに新しい値を送信する方が、関数を呼び出すよりも高速です。再帰的なコルーチンを作成することはできませんが、コルーチンをスローしValueError: generator already executingますが、コルーチンワーカーのプールを作成することはできます。ツリーのレベルごとに1人のワーカーが必要です。動作するテストコードをいくつか作成しましたが、タイミングの問題についてはまだ調べていません。

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の投稿からの純粋なPythonの代替:

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:]))

結果-2行目の「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:ループあたり317nsでキャッシュされていることを意味する可能性があります。

さらに調査した後、Pythonジェネレーターは魔法ではなく、sendは依然として関数呼び出しです。私のジェネレーターベースのメソッドがより高速であるように見えた理由は、リストに対してインプレース操作を行っていたためです。これにより、関数呼び出しが少なくなりました。

私は最近の講演でこれをたくさん書き留めました。

これがジェネレーターで遊んでみたい人に役立つことを願っています。

于 2013-03-15T15:15:45.757 に答える
3

2つの関数を別々に定義します。

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
于 2013-03-15T14:21:28.440 に答える
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
于 2017-07-02T10:55:18.923 に答える