分别定义两个函数:
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