pythonでのデータ型
タプル
タプルは複数の要素から構成される。 初期化後に内包する値に対して変更することができないimmutableなコレクションとなる
python_tuple = ( "year", "month", "day", 1, 3 ) print( python_tuple )
タプルで要素に対してアクセスする場合は配列と同じようにindexを指定してアクセスする
print( python_tuple[0] ) print( python_tuple[1] ) print( python_tuple[2] )
タプルの内包要素数はlen関数で調べることが可能
print( len( python_tuple ) )
リスト
リストはタプルと同じように複数の要素から構成される。 リストはタプルと違い内包する値に対して変更を行うことが可能なmutableなコレクションとなる
python_list = [ "year", "month", "day", 1, 3 ] print( python_list )
各要素のアクセスや要素数はタプルと同じように行える
print( python_list[0] ) print( python_list[1] ) print( python_list[2] ) print( len( python_list ) )
リストの末尾に要素を追加する場合list.append関数を使用する
python_list.append( "time" ) print( python_list )
リストの末尾に複数の要素を追加する場合list.extend関数を使用する
python_list.extend( [1, 2, 3, 5] ) print( python_list )
リストから要素を取り出す場合list.pop関数を使用する
popValue = python_list.pop( 2 ) #指定したindexの要素の値を取り出す print( python_list ) print( "popValue =" + str( popValue ) ) popValue = python_list.pop() #引数を指定しない場合末尾から取り出す print( python_list ) print( "popValue =" + str( popValue ) )
リストから要素を削除する場合list.remove関数を使用する
python_list.remove( "year" ) print( python_list )
ディクショナリ
リスト・タプルと同じ様な構造ではあるが、キーと値がセットで内包されている
ディクショナリの宣言方法
python_dict = { "year" : 2013, "month" : 3, "day" : 31 } print( python_dict )
ディクショナリ型ではタプル・リストのようにindexでのアクセスをする場合は keyを配列の演算子に指定してやる
python_dict = { "year" : 2013, "month" : 3, "day" : 31 } print( python_dict["year"] ) print( python_dict["month"] )
要素に対してアクセスする場合はdict.get関数を使用することでも取得できる
python_dict = { "year" : 2013, "month" : 3, "day" : 31 } print( python_dict.get( "day" ) ) print( python_dict.get( "ddd", "NON" ) ) #キーが見つからなかった場合第2引数を返す
要素数はタプル・リストと同じように行える
python_dict = { "year" : 2013, "month" : 3, "day" : 31 } print( len( python_dict ) )
ディクショナリに要素を追加する場合dict[key] = valueと キーに対して代入をするようにすれば追加される
python_dict = {} python_dict["year"] = 2013 python_dict["month"] = 3 python_dict["day"] = 31 print( python_dict )