It is a common requirement to make a list a tuple and vice versa.
A common practice is to use the built-in functions list
and tuple
.
l = [0, 1, 2]
t = tuple(l)
print(t)
(0, 1, 2)
However, if the list is nested, it will only tuple the shallowest hierarchy.
l = [[0, 1, 2], [3, 4, 5, 6, 7], 8, 9]
t = tuple(l)
print(t) # ((0, 1, 2), (3, 4, 5, 6, 7), 8, 9)I want you to be
([0, 1, 2], [3, 4, 5, 6, 7], 8, 9)
It's sharp.
Let's make a tuple of all layers while calling recursively.
def list_to_tuple(l):
return tuple(list_to_tuple(e) if isinstance(e, list) else e for e in l)
l = [[0, 1, 2], [3, 4, 5, 6, 7], 8, 9]
t = list_to_tuple(l)
print(t)
((0, 1, 2), (3, 4, 5, 6, 7), 8, 9)
I did it.
Actually, this article is [here](https://blog.ttk1.net/2016/05/20/python%E3%81%A7%E5%85%A5%E3%82%8C%E5%AD%90% E6% A7% 8B% E9% 80% A0% E3% 81% AElist% E3% 82% 92tuple% E3% 81% AB% E5% A4% 89% E6% 8F% 9B% E3% 81% 97% E3% 81% 9F% E3% 81% 84 /) It is a pakuri. ~~ Are you not embarrassed ~~
The difference is that the part that used the for statement and the assignment operator over there is now included.
For for statements that repeat honestly, the inclusion notation calls a dedicated process, which shortens the execution time (Reference).
def list_to_tuple_orig(_list):
t = ()
for e in _list:
if isinstance(e,list):
t += (list_to_tuple(e),)
else:
t += (e,)
return t
l = list(range(10000))
%timeit t = list_to_tuple_orig(l)
%timeit t = list_to_tuple(l)
%timeit t = tuple(l)
92.7 ms ± 576 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
877 µs ± 3.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
19.6 µs ± 47.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
It's about 100 times faster. It's a big defeat for built-in functions.
Recommended Posts