Python でのタプル内包

Vaibhav Vaibhav 2023年10月10日
Python でのタプル内包

Python プログラミング言語には、単純で理解しやすい構文があります。構文は非常に単純なので、Python を使用してワンライナーコードをすばやく記述できます。そのような機能の 1つは、リストの反復またはリストの理解です。この [i ** 2 for i in [1, 2, 3, 4, 5, 6, 7]] を実行することで、リストを反復処理し、リスト要素の正方形を含む新しいリストをすばやく返すことができます。同じことが辞書にも当てはまります。また、1 行で繰り返すこともできます。

Python には、リスト、タプルなどのさまざまな線形データ構造があります。上記のリスト内包表記は、タプルには適用されません。これは、(i ** 2 for i in (1, 2, 3, 4, 5, 6, 7)) を実行できないことを意味します。これはエラーをスローします。これが不可能な場合、Python でタプル内包を 1 行で実行するにはどうすればよいですか?この記事では同じことについて話します。

Python でのタプル内包

次の構文を使用して、Python でタプル内包を実行できます。

x = tuple(i for i in (1, 2, 3, 4, 5, 6, 7))
print(x)
print(type(x))
y = tuple(i ** 2 for i in (1, 2, 3, 4, 5, 6, 7))
print(y)
print(type(y))

出力:

(1, 2, 3, 4, 5, 6, 7)
<class 'tuple'>
(1, 4, 9, 16, 25, 36, 49)
<class 'tuple'>

Python 3.5 は、タプル内包を実行するための新しい方法を考案しました。それは開梱のプロセスを使用していました。*を使用して開梱を実行できます。同じことについては、次のコードを参照してください。

x = (*(i for i in [1, 2, 3, 4, 5, 6, 7]),)  # Notice the comma (,) at the end
print(x)
print(type(x))

出力:

(1, 2, 3, 4, 5, 6, 7)
<class 'tuple'>

この構文は、x = tuple([i for i in [1, 2, 3, 4, 5, 6, 7]]) と書くのと同じであることに注意してください。

x = tuple([i for i in [1, 2, 3, 4, 5, 6, 7]])
print(x)
print(type(x))

出力:

(1, 2, 3, 4, 5, 6, 7)
<class 'tuple'>
著者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

関連記事 - Python Tuple