セット() メソッドは、任意の反復可能要素を、一般に Set と呼ばれる個別の要素を持つ反復可能要素のシーケンスに変換するために使用されます。 Python では、set() 関数は、セットを初期化するか空のセットを作成するために使用される組み込みコンストラクターです。この記事では、Python の set() について説明し、Python で反復可能オブジェクトを一意の要素を持つシーケンスに変換する方法について説明します。 パイソン 。
Python set() メソッドの構文
構文 : セット(反復可能)
パラメーター : リスト、タプル、辞書などの反復可能なシーケンス。
戻り値 : 要素が渡されない場合は空のセット。引数として渡されたときに反復可能な非反復要素。
Pythonのset()関数とは何ですか?
セット、別個の言語からなるシーケンスを表す数学の用語は、その言語でも次のように拡張されます。 パイソン set() を使用して簡単に作成できます。 set() メソッドは、反復可能オブジェクトを Python の一意の要素を持つシーケンス (一般に Set と呼ばれます) に変換するために使用されます。これは、空のセットを作成したり、要素を含むセットを初期化したりするために使用される組み込みコンストラクター関数です。
Python set() メソッドのプロパティ
- 空のセットを作成するためにパラメータは渡されません
- 辞書はセットを使用して作成することもできますが、変換後にはキーのみが残り、値は失われます。
Python の set() 関数の例
以下は、Python で set() を使用する方法です。
- 空のセットの作成
- リストで set() を使用する
- タプルでの set() の使用
- Range を使用したセットの作成
- 辞書をセットに変換する
set() 関数を使用したセットの作成
この例では、 セット set() 関数を使用します。
Python3
# we are creating an> #empty set by using set()> > s>=> set>()> print>(>'Type of s is '>,>type>(s))> |
Linux用のgzip
>
>出力
Type of s is>
リストを使用した set() 関数
この例では、set() を使用しています。 リスト 。ここでは、Python で反復可能オブジェクトを固有の要素を持つシーケンスに変換します。
Python3
# working of set() on list> # initializing list> lis1>=> [>3>,>4>,>1>,>4>,>5> ]> > # Printing iterables before conversion> print>(>'The list before conversion is : '> +> str>(lis1))> > # Iterables after conversion are> # notice distinct and elements> print>(>'The list after conversion is : '> +> str>(>set>(lis1)))> |
Javaの配列リストをソートする
>
>出力
互換性テスト
The list before conversion is : [3, 4, 1, 4, 5] The list after conversion is : {1, 3, 4, 5}> タプルを使用した set() 関数
この例では、set() 関数を使用しています。 タプル 。
Python3
# working of set() on tuple> # initializing tuple> tup1>=> (>3>,>4>,>1>,>4>,>5>)> > # Printing iterables before conversion> print>(>'The tuple before conversion is : '> +> str>(tup1))> > # Iterables after conversion are> # notice distinct and elements> print>(>'The tuple after conversion is : '> +> str>(>set>(tup1)))> |
>
>出力
The tuple before conversion is : (3, 4, 1, 4, 5) The tuple after conversion is : {1, 3, 4, 5}> 範囲を指定した set() 関数
この例では、set() 関数を使用しています。 範囲 関数。ここでは、Python で反復可能オブジェクトを固有の要素を持つシーケンスに変換します。
Python3
# working of set() on range> > # initializing range> r>=> range>(>5>)> > r>=>set>(r)> # Iterables after conversion are> # notice distinct and elements> print>(>'The Range after conversion is : '> +> str>(r))> |
ダーツリスト
>
Javaのコレクション
>出力
The Range after conversion is : {0, 1, 2, 3, 4}> ディクショナリを使用した set() メソッドのデモ
この例では、 set() のデモを示しています。 辞書 そしてそれは機能しています。
Python3
# Python3 code to demonstrate the> # working of set() on dictionary> > # initializing list> dic1>=> {>4> :>'geeks'>,>1> :>'for'>,>3> :>'geeks'> }> > # Printing dictionary before conversion> # internally sorted> print>(>'Dictionary before conversion is : '> +> str>(dic1))> > # Dictionary after conversion are> # notice lost keys> print>(>'Dictionary after conversion is : '> +> str>(>set>(dic1)))> |
>
>出力
Dictionary before conversion is : {4: 'geeks', 1: 'for', 3: 'geeks'} Dictionary after conversion is : {1, 3, 4}>