IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

Pythonに入門してみた

Python3系です

  • 型はイラナイらしい
>>> x = 'a'
>>> x
'a'
  • パラメータにはカッコが必要
>>> x = 'a'
>>> x
'a'
>>> print x
  File "<stdin>", line 1
    print x
          ^
SyntaxError: Missing parentheses in call to 'print'
>>> print 1+1
  File "<stdin>", line 1
    print 1+1
          ^
SyntaxError: Missing parentheses in call to 'print'
>>> print (1+1)
2
>>> print (x)
a
>>> x = 'abc'
>>> print (x)
abc
  • 文字列はシングルクォーテーション、ダブルクォーテーションどちらでも良いみたい。
>>> x = 'abc'
>>> print (x)
abc
>>> 
>>> x = 'abc'
>>> print (x)
abc
>>> x = "abc"
>>> x
'abc'
>>> 
  • 真偽値は True / False (先頭大文字)
>>> true
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>> True
True
>>> False
False
>>> 
  • 配列は四角カッコ
>>> ['a','b','c']
['a', 'b', 'c']
>>> ['a','b','c',['x','y']]
['a', 'b', 'c', ['x', 'y']]
>>> 
  • ラムダ式はlambdaで書く。ファンクションオブジェクト(?)が帰るみたい。
>>> lambda x:x * 2
<function <lambda> at 0x1021b2048>
>>> x = lambda x:x * 2
>>> x 3
  File "<stdin>", line 1
    x 3
      ^
SyntaxError: invalid syntax
>>> x (3)
6
>>> 
>>> lambda x,y : x + y
<function <lambda> at 0x1021b21e0>
>>> z = lambda x,y : x + y
>>> z 2 3
  File "<stdin>", line 1
    z 2 3
      ^
SyntaxError: invalid syntax
>>> z (2,3)
5
>>> 
>>>
>>> a = "あいうえお"
>>> a
'あいうえお'
>>> 
  • mapするとmapオブジェクト(?)が帰るのでlistにする。
>>> map (lambda x:x*2, x)
<map object at 0x102195b70>
>>> print map (lambda x:x*2, x)
  File "<stdin>", line 1
    print map (lambda x:x*2, x)
            ^
SyntaxError: invalid syntax
>>> y = map (lambda x:x*2, x)
>>> y
<map object at 0x102195ba8>
>>> x
[1, 2, 3]
>>> list (map (lambda x:x*2, x) )
[2, 4, 6]
>>> 
  • mapの戻りはイタレータらしい
>>> x = [1,2,3,4,5,6,7]
>>> x = map (lambda x:x*2, x) 
>>> next(x)
2
>>> next(x)
4
>>> next(x)
6
>>> next(x)
8
>>> next(x)
10
>>> next(x)
12
>>> next(x)
14
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 
  • 計算に型がある 基本は小数で返す。 /// があり二つものは型変換がない。
>>> 3/2
1.5
>>> 1/3
0.3333333333333333
>>> 1//3
0
>>> 
  • printで改行しない
>>> print ("abc", end="")
abc>>> 
>>> 
>>> 
>>> "あ".encode('utf-8')
b'\xe3\x81\x82'
>>> "あ".encode('shift-jis')
b'\x82\xa0'
>>> import pickle
>>> my_data = (1,2)
>>> with open('data.pkl', 'wb') as f: pickle.dump(my_data, f)
... 
>>> :q
  File "<stdin>", line 1
    :q
    ^
SyntaxError: invalid syntax
>>> ^C
KeyboardInterrupt
>>> 
wk$ ls 
__pycache__ data.pkl    hr_year.csv test.png    test.py
  • たたみ込みはfunctoolsをインポートする必要がある
>>> from functools import reduce
>>> reduce((lambda x,y:x+y),[1,2,3])
6