はじめてのPython(6)
タプル
#coding: UTF-8 #タプルの作成 tpl = (2005, 2006, 2007, 2008) tpl2 = (2005,) print tpl print tpl2 #リストの要素を取得 print tpl[0] #2005 print tpl[1] #2006 #タプルはリストと異なり、別のオブジェクトの代入ができない # tpl[1] = "b" #NG #スライスを用いた要素の取得 print tpl[1:3] #(2006,2007) #タプルのサイズを取得 print len(tpl) #4 #タプルの結合 newtpl = tpl + (2009,2010) print newtpl #(2005,2006,2007,2008,2009,2010) newtpl2 = tpl2 * 2 print newtpl2 #(2005,2005) #tuple関数を使ったタプルの作成 print tuple("ABC") print tuple([20,18]) #ソート済みタプル作成 #一度リストオブジェクトでソートしてからタプルを作る t = list("BAC") t.sort() t = tuple(t) print t