今さらPython3 (12) - リストその1

やっと第3章に突入。年末だしスピードアップしたいところ。

入門 Python 3

入門 Python 3

リスト事始め

>>> empty_list = []
>>> weekedays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
>>> big_birds = ['emu', 'ostrich', 'cassowary']
>>> first_names = ['Graham', 'John', 'Terry', 'Terry', 'Michael']
>>> another_empty_list = list()
>>> another_empty_list
[]

空っぽのリストを作るときは、[]を渡してやれば良いんだけど、list()の方が美しく見えるなぁ。(実際に使ったことないけど)
順序が大事ではないときは、setとかdictionaryの使用を検討しましょう。ま、そうだね。

>>> list('cat')
['c', 'a', 't']
>>> a_tuple = ('ready', 'fire', 'aim')
>>> list(a_tuple)
['ready', 'fire', 'aim']

上のパターンは、文字列をリスト化していて、一文字ずつリスト化されていると。下のヤツは、タプルをリスト化する。イミュータブルなタプルをリスト化して編集する感じでしょ。

>>> birthday = '1/6/1952'
>>> birthday.split('/')
['1', '6', '1952']
>>> splitme = 'a/b//c/d///e'
>>> splitme.split('/')
['a', 'b', '', 'c', 'd', '', '', 'e']
>>> splitme.split('//')
['a/b', 'c/d', '/e']

続いては、split()関数を使って文字列をリスト化しているパターンと。スプリッタに使う文字は何も1文字である必要はないというのは、ちょいとした気づき。ただ、この章の主旨から外れるけど、birthdayは年、月、日に別れてくれた方がいいよね。

>>> month, day, year = tuple(birthday.split('/'))
>>> month
'1'
>>> day
'6'
>>> year
'1952'
>>> month, day, year = birthday.split('/')
>>> month
'1'
>>> day
'6'
>>> year
'1952'

うん。実際のプログラムだったら、この方がうれしい。これ、tupleじゃないと出来ないのかと思っていたけど、listでもいけるのね。

スライスの時間ですよ

>>> marxes = ['Groucho', 'Chico', 'Harpo']
>>> marxes[0]
'Groucho'
>>> marxes[1]
'Chico'
>>> marxes[2]
'Harpo'
>>> marxes[-1]
'Harpo'
>>> marxes[-2]
'Chico'
>>> marxes[-3]
'Groucho'

これは文字列でやったときと同じ。あ、これだとスライスしてないか。

>>> marxes[1:3]
['Chico', 'Harpo']

はい、スライス成立。

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

範囲から外れたら怒られます。そらそうでしょ。

入れ子のリスト

リストの中にリスト。入れ子構造も出来ますよって話ですね。

>>> small_birds = ['hummingbird', 'finch']
>>> extinct_birds = ['dodo', 'passenger pigeon', 'Norwegian Blue']
>>> carol_birds = [3, 'French hens', 2, 'turtledoves']
>>> all_birds = [small_birds, extinct_birds, 'macaw', carol_birds]
>>> 
>>> all_birds
[['hummingbird', 'finch'], ['dodo', 'passenger pigeon', 'Norwegian Blue'], 'macaw', [3, 'French hens', 2, 'turtledoves']]

入れ子の子どもから値を拾う場合は、こんなやり方。

>>> all_birds[1]
['dodo', 'passenger pigeon', 'Norwegian Blue']
>>> all_birds[1][0]
'dodo'

[]に入ったインデックスを並べてあげれば良し。

(つづく)