リスト型と値

[ edit ]

リスト型のデータ・リテラル

[ edit ]

>>> [1,2,3,4]
[1, 2, 3, 4]

>>> x  = [1,2,3,4,5]
>>> print(x)
[1, 2, 3, 4, 5]

>>> [1,"a",2,"b",3]
[1, 'a', 2, 'b', 3]

>>> [1,"a",[2,3],["b","c"],4,5]
[1, 'a', [2, 3], ['b', 'c'], 4, 5]

>>> [[1,2,3],[4.5,6],[7,8,9]]
[[1, 2, 3], [4.5, 6], [7, 8, 9]]

リスト型の値

[ edit ]

>>> list()
[]

>>> type( [1,2,3,4,5] )
<class 'list'>

>>> [0]*5
[0, 0, 0, 0, 0]

>>> []+[1]+[2]+[3]+[4]+[5]
[1, 2, 3, 4, 5]

>>> s = []
>>> s.append(1)
>>> s.append(2)
>>> s.append(3)
>>> s.append(4)
>>> s.append(5)
>>> s
[1, 2, 3, 4, 5]


リストの操作

要素へのアクセス

[ edit ]

添え字(インデックス)によるアクセス

>>> x = ["a","b","c","d","e","f","g"]

>>> x[0]
'a'

>>> x[4]
'e'

>>> x[len(x)-1]
'g'

>>> x = ["a","b","c","d","e","f","g"]

>>> x[4]
'e'

>>> x[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

>>> x[len(x)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

各要素への順次アクセス

>>> x = [1, 2, 3, 4, 5]

>>> for e in x: print( e * 2 )
...
2
4
6
8
10

x = [1, 2, 3, 4, 5]

for e in x:
    print( e )

>>> x = [1, 2, 3, 4, 5]

>>> for i in range( len( x ) ): print( x[i] * 2 )
...
2
4
6
8
10

>>> x = [1, 2, 3, 4, 5]

>>> for i in range( len( x ) + 3 ): print( x[i] * 2 )
...
2
4
6
8
10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

x = [1, 2, 3, 4, 5]

for i in range( len( x ) ): 
    print( x[i] )

>>> x = [1, 2, 3, 4, 5]

>>> [ e*2 for e in x]
[2, 4, 6, 8, 10]

>>> x = [1, 2, 3, 4, 5]

>>> print( list( map( lambda e: e*2, x) ) )
[2, 4, 6, 8, 10]

部分列(スライス)アクセス

[ edit ]

>>> x = ["a","b","c","d","e","f","g","h","i"]

>>> x[2:6]
['c', 'd', 'e', 'f']

>>> x[:6]
['a', 'b', 'c', 'd', 'e', 'f']

>>> x[2:]
['c', 'd', 'e', 'f', 'g', 'h', 'i']

>>> x = ["a","b","c","d","e","f","g","h","i"]

>>> x[2:6:2]
['c', 'e']

>>> x[2::2]
['c', 'e', 'g', 'i']

>>> x[::2]
['a', 'c', 'e', 'g', 'i']

>>> x = ["a","b","c","d","e","f","g","h","i"]

>>> x[-1]
'i'

>>> x[-2]
'h'

>>> x[-5:-1]
['e', 'f', 'g', 'h']

>>> x[-5:-1:2]
['e', 'g']

>>> x[-5:-1:-2]
[]

リストの操作 (変更可能なシーケンス操作)

[ edit ]

リストの操作: 連結(+)

>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]

>>> [1,2,3]+["a","b","c"]
[1, 2, 3, 'a', 'b', 'c']

リストの操作: リストの要素数(len)

>>> len([1,2,3,4,5])
5

>>> len([1,2,[3,4,[5,6],7],8])
4

SoftEng: Python/Lang/DataType/Sequence/List/Contents (last edited 2018-11-03 01:16:39 by TadashiIijima)