LoginSignup
18
23

More than 5 years have passed since last update.

Python 基礎文法(雑)めも

Posted at

2.7 ベース。

組み込み型

# 整数
a = 10
i = -10
x = 0x55
b = 0x100110

# 浮動小数
f = 2.73

# ブール
a = True
b = False

# 文字列(不変)
s = 'python'

# リスト(可変)
a = ['p','y','t','h','o','n']

# タプル(不変)
a = ('p','y','t','h','o','n')

# ディクショナリ(可変)
a = {'happy' : '(^^)', 'sad' : '(TT)'}
print a['happy']

不変性と可変性

文字列やタプルの一部を後から変更することはできない。
再代入は可能。参照されなくなったデータは GC の対象となる。

>>> a = ('p','y','t','h','o','n')
>>> a[0]
'p'
>>> a[0] = 'b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# これは OK
>>> a = ('b','y','t','h','o','n')

浮動小数の丸め

>>> a = 1.23456
>>> round(a)
1.0
>>> round(a, 1)
1.2
>>> round(a, 4)
1.2346

整数の基本サイズ(環境依存)の取得

>>> import sys
>>> print sys.maxint
9223372036854775807
>>> print bin(sys.maxint)
0b111111111111111111111111111111111111111111111111111111111111111
>>> print hex(sys.maxint)
0x7fffffffffffffff

文字列

インデックス、スライス

>>> a = 'python'
>>> a[0]
'p'
>>> a[-1]
'n'

# 文字列やリストは範囲指定できる。「スライスで指定する」という
>>> a[1:3]
'yt'
>>> a[1:]
'ython'
>>> a[:3]
'pyt'

置換、連結、繰り返し

>>> a = 'python'
>>> a += ' python'
>>> a
'python python'
>>> a.replace('p', 'b')
'bython bython'

# 破壊されない
>>> a
'python python'

>>> b = a * 3
>>> b
'python pythonpython pythonpython python'
>>> a
'python python'

len, find, in

# 文字列長
>>> a = 'python'
>>> len(a)
6

# 存在確認:in または find を使う
>>> 'py' in a
True
>>> 'pi' in a
False

>>> a = 'hello python!'
>>> a.find('py', 0, 3) # 0-3番目に py が存在するか
-1
>>> a.find('py', 2) # 2番目から最後までの間に py が存在するか、存在する場合はインデックスを返す
6

リスト

他言語の配列と違い、異なる型を持つことができる

>>> a = [1, 2, 'python', 1.234]
>>> a[0]
1
>>> a[-1]
1.234
>>> a[2]
'python'

リストの入れ子

>>> a = [1, 2, [3, 4, 5, 6]]
>>> a[2][2]
5

リストのスライス指定

>>> a = [1, 2, 3, 4]
>>> a[0:2]
[1, 2]

# 要素数が1でも当然リストとして返る
>>> a[3:]
[4]

# スライスで要素入れ替え
>>> a[0:2] = [0,0]
>>> a
[0, 0, 3, 4]

# スライス指定の範囲より要素数が大きくても挿入される
>>> a[0:2] = [0,0,0,0]
>>> a
[0, 0, 0, 0, 3, 4]

append, extend, del, pop, reverse

すべて破壊的メソッド

>>> a = [0, 1, 2, 3]
>>> a.append(5)
>>> a
[0, 1, 2, 3, 5]

# 複数追加するには extend を使う
>>> a.extend([6,7])
>>> a
[0, 1, 2, 3, 5, 6, 7]

# インデックスを指定して削除
>>> del a[2]
>>> a
[0, 1, 3, 5, 6, 7]

# 最後尾の要素を pop
>>> a.pop()
7
>>> a
[0, 1, 3, 5, 6]

a.reverse()
>>> a
[6, 5, 3, 1, 0]

sort

ASCII でソート

>>> a = [2.4, 1, 'Python', 'A', 3]
>>> a.sort()
>>> a
[1, 2.4, 3, 'A', 'Python']

# 降順で
>>> a.sort(reverse = True)
>>> a
['Python', 'A', 3, 2.4, 1]

タプル

括弧は省略可能だが、可読性のために書いた方がよい。
入れ子やスライスでのアクセスはリストと同様

a = ('p','y','t','h','o','n')
>>> a[0]
'p'
>>> a[-1]
'n'
>>> a[0:2]
('p', 'y')
>>> a[:3]
('p', 'y', 't')

# 連結や繰り返しの演算子も文字列と同様
>>> b = ('h', 'e', 'y')
>>> a + b
('p', 'y', 't', 'h', 'o', 'n', 'h', 'e', 'y')
>>> b * 3
('h', 'e', 'y', 'h', 'e', 'y', 'h', 'e', 'y')

タプルとリストの変換

>>> a = (1, 2, 3)
>>> b = list(a)
>>> b
[1, 2, 3]

>>> a = tuple(b)
>>> a
(1, 2, 3)

ディクショナリ

ハッシュデスネ。

>>> a = {'happy' : '(^^)', 'sad' : '(TT)'}
>>> a['happy']
'(^^)'

# 値が無いキーが返すのはNULLでなくエラー
>>> a['angry']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 0

# 追加・削除
>>> a['sleepy'] = '(=_=)'
>>> a
{'sad': '(TT)', 'sleepy': '(=_=)', 'happy': '(^^)'}

>>> del a['sad']
>>> a
{'sleepy': '(=_=)', 'happy': '(^^)'}

>>> a.pop('happy')
'(^^)'
>>> a
{'sleepy': '(=_=)'}

文字列フォーマット

% 演算子と format() メソッド

>>> a = 10.234
>>> '%d' % a
'10'
>>> '%.2f ' % a
10.23
>>> "%x" % a
'a'
>>> "%s" % a
'10.234'

# 複数のデータを挿入するときはタプルで渡す
>>> a = 7
>>> b = 'python'
>>> msg = '%d wonders of the %s' % (a, b)
>>> msg
'7 wonders of the python'

# '{}' に書式指定文字列を入れて format(変数)
>>> a = python
>>> '{:s}'.format(a) 
'python'

>>> '{}'.format(a)  # 書式指定なし
'python'

>>> a = 10.234
>>> '{:f}'.format(a)
'10.234000'
>>> '{:.2f}'.format(a)
'10.23'

# フォーマットが違うとエラーになる
>>> '{:d}'.format(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'float'

# 複数の変数はタプルで
>>> b = 4.444
>>> '{:.2f}, {:.3f}'.format(a,b)
'10.23, 4.444'

# {}内にフィールド名としてインデックスを記述する方法も取られる。引数の先頭から0,1,2,,となる
>>> a = "Raspberry Pi"
>>> b = "Python"
>>> c = "in"
>>> '{1} {2} {0}'.format(a,b,c)
'Python in Raspberry Pi'

ヌルオブジェクト

NULL でも nil でもなく、None

>>> n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'nn' is not defined
>>> n = None
>>> n
# なにも表示されないがエラーではなくなる
18
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
23