チュートリアルその1 ぱらぱらめくるPython3.4.3

python
    • と打てばpython2系が
python3.4
    • と打てばpython3.4が立ち上がる
  • 3 形式ばらないイントロ
>>> a = 5+3j
>>> b = 2+1j
>>> a*b
(7+11j)
    • 番地の扱い、0あり、負の数あり、[min,max)と初めは含み終わりは含まない。逆向きスライシングはだめ
>>> x = [1,2,3,4]
>>> x[0]
1
>>> x[1]
2
>>> x[-1]
4
>>> x[0:2]
[1, 2]
>>> x[1:3]
[2, 3]
>>> x[2:0]
[]
>>> x[2:]
[3, 4]
>>> x[:4]
[1, 2, 3, 4]
>>> x[:10]
[1, 2, 3, 4]
>>> x[:3]
[1, 2, 3]
>>> x[:]
[1, 2, 3, 4]
>>> [1,2,3]+[4,5]
[1, 2, 3, 4, 5]
>>> x = [1,2,3,4,5]
>>> x[2:3] = []
>>> x
[1, 2, 4, 5]
    • 対話モードで複数業入力、とか
>>> a,b = 0,1 # 複数の変数に付値
>>> while b < 10: # ":"は継続するよ、の印
...   print(b) # "..."は継続中ですが受け付けますよ、というプロンプト
while構文のループの中なので、複数個の空白文字などでインデントされている("..."とprintの冒頭の間に空白文字がある)ことに注意
...   a,b = b,a+b
... # 継続中プロンプトに何もいれずにリターンすると、入力終了と判断し、全体を実行
1
1
2
3
5
8
  • 4 その他の制御フロー
    • if elif
      • ":"が何度も現れていることに注意。インデントに注意
>>> a = 3
>>> if(a>0):
...   print(a)
... elif(a==0):
...   print('zero')
... else:
...   print(-a)
... 
3
    • for elem in seq:
>>> x = [1,3,5,7]
>>> for i in x:
...   print(i^2,end=';')
... 
3;1;7;5;>>> 
    • for loopにはrange()を使う
>>> x = [3,1,2,4]
>>> for i in range(len(x)):
...   print(x[i],end=',')
... 
3,1,2,4,>>> 
    • range()関数は[a,b)についてby cなるシークエンス発生の関数で、aにはデフォルト値があり、それは0、cのデフォルト値は1
      • 0,1,2,...,100を作るには
>>> range(101)
range(0, 101)
>>> for i in range(101):
...   print(i,end=" ")
... 
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 >>> 
      • 3,4,5,6を作るには
>>> range(3,7)
range(3, 7)
>>> for i in range(3,7):
...  print(i,end=" ")
... 
3 4 5 6 >>> 
      • 0,2,4,6,...,10を作るには
>>> range(0,11,2)
range(0, 11, 2)
>>> for i in range(0,11,2):
...   print(i,end=" ")
... 
0 2 4 6 8 10 >>> 
      • 0,0.1,0.2,...,1を作るには
        • これは何かもっとよい方法がありそうだが…
>>> for i in range(11):
...   print(i/10,end=" ")
... 
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 >>> 
    • range()はiteratorと呼ばれる仕組みで、要素を持っているわけではなくて、「要素を返す仕組みを持っている」。したがって
>>> x = range(10)
>>> x
range(0, 10)
      • のように、xの中身を見ても"range(0,10)"となっていて、0,1,2,...,9ではない。これをリストにするには
>>> x = list(range(10))
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    • 関数の定義はdef
>>> def mysum(x,y):
...   return x+y
... 
>>> mysum(3,4)
7
    • 関数を返す関数も作れる。lamda関数を使う
>>> def myf1(a):
...   return lambda x: x+a
... 
>>> myf1(2)
<function myf1.<locals>.<lambda> at 0x1006c01e0>
>>> myf2 = myf1(2)
>>> myf2(4)
6
    • 関数のdocumentのための文字列
      • ある書式で関数の説明を書いておくと、ドキュメントが簡単に作れるようになっているので、それにならう癖をつけると便利
        • 1行で書いた、関数の仕事の簡潔な説明
        • 大文字始まり、ピリオド終わり
        • help()で呼び出せる
>>> def mysum(x,y):
...     """Return sum of two args."""
...     return x+y
... 
>>> mysum
<function mysum at 0x10050cbf8>
>>> help(mysum)
        • help()で呼び出した結果
Help on function mysum in module __main__:

mysum(x, y)
    Return sum of two args.
(END) 
      • 複数行にしたいなら、第一行を主要行とし、一行空けた上で、以降の行を入れる
>>> def mysum(x,y):
...     """Return sum of two args.
...     
...     Two args, x and y, should be 
...     handled by function sum()."""
...     
...     return x+y
... 
>>> mysum(3,4)
7
>>> help(mysum)
      • このhelp()の結果
Help on function mysum in module __main__:

mysum(x, y)
    Return sum of two args.
    
    Two args, x and y, should be 
    handled by function sum().
(END) 
    • コーディングのエッセンス(詳しくはここガイドラインがある)→詳しくは後章で
      • インデントは空白x4
      • 1行は79文字まで
      • コードブロックの区切りに空行
      • 演算子の前後とコンマの後には空白を入れ、括弧類のすぐ内側には空白を入れないこと: a = f(1, 2) + g(3, 4)
      • selfをメソッドの第一引数として使う
  • 5 データ構造
    • 内容
      • リスト
      • del文という仕事
      • タプルとシークエンス
      • 集合
      • 辞書(ハッシュみたいなもの?)
    • リストの操作色々
>>> x = [1,2,3,4]
>>> x.append(6)
>>> x
[1, 2, 3, 4, 6]
>>> x[len(x):] = [8,9]
>>> x
[1, 2, 3, 4, 6, 8, 9]
>>> x.append(7,5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (2 given)
>>> x.append([7,5])
>>> x
[1, 2, 3, 4, 6, 8, 9, [7, 5]]
>>> x.extend([7,5])
>>> x
[1, 2, 3, 4, 6, 8, 9, [7, 5], 7, 5]
>>> x = list(range(1,11))
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x.append(20)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]
>>> x.pop()
20
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x.extend([20,30])
>>> x.pop(11)
30
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]
>>> x = list(range(1,11))
>>> 
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x.append(20)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20]
>>> x.pop()
20
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x.extend([20,30])
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]
>>> x.pop(10)
20
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30]
>>> x.insert(50)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)
>>> x.insert(50,0))
  File "<stdin>", line 1
    x.insert(50,0))
                  ^
SyntaxError: invalid syntax
>>> x.insert(50,0)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30, 0]
>>> x.pop()
0
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30]
>>> x.insert(0,50)
>>> x
[50, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30]
>>> x.insert(3,60)
>>> x
[50, 1, 2, 60, 3, 4, 5, 6, 7, 8, 9, 10, 30]
>>> x.pop(3)
60
>>> x
[50, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 30]
>>> x.insert(5,1)
>>> x
[50, 1, 2, 3, 4, 1, 5, 6, 7, 8, 9, 10, 30]
>>> x.index(1)
1
>>> x.remove(1)
>>> x
[50, 2, 3, 4, 1, 5, 6, 7, 8, 9, 10, 30]
>>> x.index(1)
4
>>> x[3:5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
>>> x[3:7] = rep(1,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'rep' is not defined
>>> rep(1,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'rep' is not defined
>>> x[3:7] = [1,1,1]
>>> x
[50, 2, 3, 1, 1, 1, 7, 8, 9, 10, 30]
>>> x.count(1)
3
>>> x.sort()
>>> x
[1, 1, 1, 2, 3, 7, 8, 9, 10, 30, 50]
>>> x.reverse()
>>> x
[50, 30, 10, 9, 8, 7, 3, 2, 1, 1, 1]
>>> xcopy = x.copy()
>>> xcopy
[50, 30, 10, 9, 8, 7, 3, 2, 1, 1, 1]
>>> x2 = x
>>> x = [1,2]
>>> x
[1, 2]
>>> x2
[50, 30, 10, 9, 8, 7, 3, 2, 1, 1, 1]
>>> xcopy
[50, 30, 10, 9, 8, 7, 3, 2, 1, 1, 1]
>>> 
      • リスト、ポップ、スタック、キュー。fisrt-in,first-out, last-in,last-out
        • リストはスタックだけ。スタックとキューを両方やりたければ、deque
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> x.append(11)
>>> x.append(12)
>>> x.pop()
12
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> x.pop()
11
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> from collections import deque
>>> x = list(range(1,11))
>>> xq = deque(x)
>>> xq
deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> xq.popleft()
1
>>> xq
deque([2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> xq.popleft()
2
>>> xq
deque([3, 4, 5, 6, 7, 8, 9, 10])
>>> xq.pop()
10
>>> xq
deque([3, 4, 5, 6, 7, 8, 9])
>>> xq.popleft()
3
>>> xq
deque([4, 5, 6, 7, 8, 9])
    • リストに内包表現がある
      • 3の倍数のリストを作るのも簡単
>>> x = [x for x in range(100) if x % 3 == 0]
>>> x
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
    • タプルはリストとともにシークエンス
      • リスト、タプル、イテレータであるrange
      • タプルの付値はちょっとかわっている
>>> t = 1, 3, 5
>>> t
(1, 3, 5)
    • 集合
      • 順番に意味がない
>>> x = {1,2,3,4}
>>> x
{1, 2, 3, 4}
>>> x = {3,2,1,4}
>>> x
{1, 2, 3, 4}
      • 内包表現もある
>>> x = {x for x in range(100) if x % 9 ==0}
>>> x
{0, 99, 36, 72, 9, 45, 81, 18, 54, 90, 27, 63}
    • 辞書
      • 辞書はキーと値の組の集合なので、集合として定義することもできるし、dict()を使って作ることもできる
      • 同じキーに複数回値を与えると、後の値が採用される(?)
      • 2要素タプルのリストをdict()に渡して作る
      • 内包表現もある
# 集合として作る
>>> d = {0:'a',1:'b',0:'c',3:'d'}
>>> d
{0: 'c', 1: 'b', 3: 'd'}
>>> d = dict([(0,'a'),(1,'b'),(2,'a')])
>>> d
{0: 'a', 1: 'b', 2: 'a'}
>>> d = {x:x**2 for x in range(10)}
>>> d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
    • シークエンスなオブジェクトを二つ一緒にループさせる
>>> list1 = range(3,8)
>>> list2 = range(4,9)
>>> list1
range(3, 8)
>>> for a, b in zip(list1,list2):
...   print (a*b)
... 
12
20
30
42
56