Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What is going on with this article?
@BlueRayi

# 【Python】ネストしたリストをタプルにしたい

More than 1 year has passed since last update.

リストをタプルにしたり、その逆にタプルをリストにするのはよくある要求です。

## 一般的な方法

```l = [0, 1, 2]
t = tuple(l)
print(t)
```
```(0, 1, 2)
```

## この方法の問題

ところが、リストがネストしていた場合、最も浅い階層しかタプルにしてくれません。

```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) になってほしい
```
```([0, 1, 2], [3, 4, 5, 6, 7], 8, 9)
```

キレそ。

## ネストしたリストを内部ごとタプルにする関数

```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)
```

やったぜ。

## 元ネタとその比較

```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)
```

100 倍くらい早くなっていますね。 組み込み関数には大敗北ですが。

5
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
アマグラマ。大学では化け学を専攻。