タプル型と値

edit

タプル(tuple)型のデータ

タプルの生成

edit

>>> 1,2
(1, 2)

>>> 1,2
(1, 2)

>>> (1)
1

>>> (1,)
(1,)

>>> ()
()

>>> type( (1,2) )
<class 'tuple'>

>>> type( (1) )
<class 'int'>

>>> type( (1,) )
<class 'tuple'>

>>> type( () )
<class 'tuple'>

>>> (x,y)= divmod( 99, 5 )

>>> x
19

>>> y
4

タプルの生成

>>> tuple()
()

>>> x = tuple( range( 2,8,2 ) )

>>> x
(2, 4, 6)

>>> type( x )
<class 'tuple'>

タプルは要素を変更できない(イミュータブル)

>>> data_list  = ["a","b","c","d","e"]
>>> data_list[3]
'd'
>>> data_list[3] = "x"
>>> data_list
['a', 'b', 'c', 'x', 'e']

>>> data_tuple  = ("a","b","c","d","e")
>>> data_tuple[3]
'd'
>>> data_tuple[3] = "x"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> data_tuple
('a', 'b', 'c', 'd', 'e')


タプル(tuple)の操作

リストとの相互変換

edit

>>> x = list( ("a","b","c","d","e") )

>>> x
['a', 'b', 'c', 'd', 'e']

>>> type( x )
<class 'list'>

>>> x = list( ("a","b",("c","d"),"e") )

>>> x
['a', 'b', ('c', 'd'), 'e']

>>> type( x )
<class 'list'>

>>> x = tuple( ["a","b","c","d","e"] )

>>> type( x )
<class 'tuple'>

>>> x = tuple( ["a",["b","c"],"d","e"] )

>>> x
('a', ['b', 'c'], 'd', 'e')

>>> type( x )
<class 'tuple'>

SoftEng: Python/Lang/DataType/Sequence/Tuple/Contents (last edited 2018-10-01 23:50:22 by TadashiIijima)