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